Pass column name in data.table using variable [duplicate]
Possible Duplicate:
Variably selecting/assigning to fields in a data.table
In following example, I am creating a data table having column name ‘x’ and ‘v’
library('data.table')
DT <- data.table(x = c("b","b","b","a","a"), v = rnorm(5))
I can access values of column ‘x’ by :
DT[ , x]
# [1] "b" "b" "b" "a" "a"
But if I want to access by passing through a variable, it doesn’t work
temp <- "x"
DT[ , temp]
# [1] "x"
There would be multiple columns and I will have to select values for only couple of them. These column names I will be provide by passing through a R module.
Never mind, I got it, it should be:
DT[ , get(temp)]
Use the quote()
and eval()
functions to pass a variable to j
. You don't need double-quotes on the column names when you do it this way, because the quote()
-ed string will be evaluated inside the DT[]
temp <- quote(x)
DT[ , eval(temp)]
# [1] "b" "b" "b" "a" "a"
With a single column name, the result is a vector. If you want a data.table result, or several columns, use list form
temp <- quote(list(x, v))
DT[ , eval(temp)]
# x v
# 1: b 1.52566586
# 2: b 0.66057253
# 3: b -1.29654641
# 4: a -1.71998260
# 5: a 0.03159933
참고URL : https://stackoverflow.com/questions/12603890/pass-column-name-in-data-table-using-variable
'your programing' 카테고리의 다른 글
How to center vector drawable in layer-list without scaling (0) | 2020.09.25 |
---|---|
Anyone have a diff algorithm for rendered HTML? [closed] (0) | 2020.09.25 |
Restrict Login Email with Google OAuth2.0 to Specific Domain Name (0) | 2020.09.25 |
Simple Explanation for the “Reactor Pattern” with its Applications [closed] (0) | 2020.09.25 |
JavaScript Exception Handling (0) | 2020.09.25 |