问题
raw
is a data.table
and the following code works:
raw[,r_responseTime] #Returns the whole column
raw[,c_filesetSize] #Same as above, returns column
plot(raw[,r_responseTime]~raw[,c_filesetSize]) #draws something
Now I want to specify these columns from a string, so for example:
col1="r_reponseTime"
col2="c_filesetSize"
How can I now achieve the same as above while referencing the columns by the string?
raw[,col1] #Returns the whole column
raw[,col2] #Same as above, returns column
plot(raw[,col1]~raw[,col2]) #draws something
Does not work, of course because I need some kind of "dereferencation". I didn't know what to search in the help and the internet, so sorry for the dumb question.
回答1:
It would be nice if you had provided a reproducible example, or at the very least shown what the column names of raw
are and what r_responseTime
and c_filesetSize
contain. This being said, get
is your function for dereferencing so give these a try:
raw[, get(col1)]
raw[, get(col2)]
plot(raw[, get(col1)] ~ raw[, get(col2)])
回答2:
A modern approach is to use ..
:
raw[ , ..col1]
..
"looks up a level" to find col1
.
An older, less preferred alternative is to use the match()
function or %in%
operator.
raw[, match(col1, names(raw)),with=FALSE]
回答3:
If you have a vector of strings, you can use mget
cols = c("r_reponseTime", "c_filesetSize")
raw[, mget(cols)]
回答4:
Unfortunately "get" can be problematic! See example below:
m = 100
x1 = sample(c("cat", "dog", "horse"), m, replace=TRUE)
y1 = rnorm(m)
fill1 = sample(c("me", "myself", "dude"), m, replace=TRUE)
df = data.frame("x"=x1, "y"=y1, "fill"=fill1)
dt = data.table(df)
get does not work!
y = "y"
dt[ , get(y)]
get works!
yCol = "y"
dt[ , get(yCol)]
works always, but it's not pretty!
eval(parse(text = paste0("values = dt[ ,", y, "]")))
eval(parse(text = paste0("values = dt[ ,", yCol, "]")))
来源:https://stackoverflow.com/questions/9864055/get-columns-by-string-from-data-table