0

I am a beginner in R. I have a table that looks like this:

> means
        as  er op rt
a 34.66667 3.5 87  4
b 22.66667 4.5  9  5
c  5.00000 7.5  6  9
d  6.00000 0.5  6  3
e  3.00000 8.0  7 89

and another one that looks like this:

> table
  exp ctrl
1  as   er
2  rt   op

I want to extract the values from the columns in "means" that are indicated in column "exp" of "table", like this:

> means_exp <- means[, table$exp]

In the real situation both tables would be much bigger, so I don't want to just specify the names of the columns to extract one by one.

However, with that command I am getting this:

> means_exp
        as  er
a 34.66667 3.5
b 22.66667 4.5
c  5.00000 7.5
d  6.00000 0.5
e  3.00000 8.0

but I am supposed to get columns "as" and "rt", not "as" and "er"

Any idea why the wrong columns are extracted?

Thank you!

Here is the dput of the first table:

structure(c(34.6666666666667, 22.6666666666667, 5, 6, 3, 3.5, 
4.5, 7.5, 0.5, 8, 87, 9, 6, 6, 7, 4, 5, 9, 3, 89), .Dim = c(5L, 
4L), .Dimnames = list(c("a", "b", "c", "d", "e"), c("as", "er", 
"op", "rt")))

and that of the second:

structure(list(exp = structure(1:2, .Label = c("as", "rt"), class = "factor"), 
    ctrl = structure(1:2, .Label = c("er", "op"), class = "factor")), .Names = c("exp", 
"ctrl"), class = "data.frame", row.names = c(NA, -2L))
arielle
  • 915
  • 1
  • 12
  • 29

1 Answers1

1

The reason the OP got different columns with the 'exp' column in 'table' is the class of the exp. It would be factor class, so converting to character is an option.

 means[,as.character(table$exp)]

The factor gets coerced to integer and we get

as.integer(factor(table$exp))
#[1] 1 2

means[,factor(table$exp)]
#       as  er
#a 34.66667 3.5
#b 22.66667 4.5
#c  5.00000 7.5
#d  6.00000 0.5
#e  3.00000 8.0

So, it selects the first 2 columns instead of the 'as' and 'rt'

akrun
  • 874,273
  • 37
  • 540
  • 662