简体   繁体   English

R data.table 使用变量名称作为 data.table 名称的向量?

[英]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.我想使用一个变量作为 df 名称,但不知道如何。 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. vector1 是我想将列数据放入vector2 的data.tables 的名称。

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.每次通过循环保持列名相同时更改 data.table 名称。

'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'根据 OP 帖子中的更新,使用mget (将所有对象的值返回到命名列表中)或get (对于单个元素 - 可以在for循环中使用)返回数据集名称的值,即'one ', '二三'

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 asfor循环中,它可以完成为

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

This replaces 'vector2' in each iteration and gets the last columnname ie from 'three'.这将在每次迭代中替换“vector2”并获取最后一个列名,即来自“three”。 If we need to create a single vector如果我们需要创建单个向量

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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