简体   繁体   中英

R data.table to vector using variable name as data.table name?

I want to use a variable as the df name but cant figure out how. I can do it this way

 'vector2 <- df$columname'

If i want to do it in a loop looking at different data tables i cant do it. vector1 is the names of my data.tables that i want to put the column data into a vector2.

I want the loop to do this

 'vector2 <- one$columname'
 'vector2 <- two$columname'
 'vector2 <- three$columname'

changing the data.table name each time it goes through the loop keeping column name the same.

'vector1<- c("one","two","three")
for(i in vector1) {
vector2 <- vector1$columname
}'

Based on the updated in OP's post, use either mget (returns the values of all the objects into a named list) or get (for a single element - can be used within for loop) to return the values of the dataset names ie 'one', 'two', 'three'

lst1 <- lapply(mget(vector1), function(x) x$columname)

If it should be a single vector

vector2 <- unlist(lst1)

In a for loop, it can be done as

for(i in vector1) vector2 <- get(i)$columname

This replaces 'vector2' in each iteration and gets the last columnname ie from 'three'. If we need to create a single vector

vector2 <- c()
for(i in vector1) vector2 <- c(vector2, get(i)$columname)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM