在R循环中访问变量数据帧

问题描述:

如果我正在循环中使用数据帧,那么如何使用可变数据帧名称(以及变量列名称)来访问数据帧内容?

If I am working with dataframes in a loop, how can I use a variable data frame name (and additionally, variable column names) to access data frame contents?

dfnames <- c("df1","df2")

df1 <- df2 <- data.frame(X = sample(1:10),Y = sample(c("yes", "no"), 10, replace = TRUE))

for (i in seq_along(dfnames)){
    curr.dfname <- dfnames[i]

    #how can I do this:
    curr.dfname$X <- 42:52

    #...this
    dfnames[i]$X <- 42:52

    #or even this doubly variable call
    for (j in 1_seq_along(colnames(curr.dfname)){
        curr.dfname$[colnames(temp[j])] <- 42:52
    }
}


可以使用 get()根据其名称的字符串返回变量引用:

You can use get() to return a variable reference based on a string of its name:

> x <- 1:10
> get("x")
[1]  1  2  3  4  5  6  7  8  9 10

所以,是的,你可以通过 dfnames 来迭代,如:

So, yes, you could iterate through dfnames like:

dfnames <- c("df1","df2")
df1 <- df2 <- data.frame(X = sample(1:10), Y = sample(c("yes", "no"), 10, replace = TRUE))

for (cur.dfname in dfnames)
{
    cur.df <- get(cur.dfname)

    # for a fixed column name
    cur.df$X <- 42:52

    # iterating through column names as well
    for (j in colnames(cur.df))
    {
        cur.df[, j] <- 42:52
    }
}

我真的认为这将是一个痛苦的尽管如此如评论者所说,如果您可以将数据框架列入列表中,然后重复执行,则可能会执行更好,更易读。不幸的是, get()不是我所知道的矢量化,所以如果你只有一个字符串列表的数据框架名称,你必须迭代获取数据框架列表:

I really think that this is gonna be a painful approach, though. As the commenters say, if you can get the data frames into a list and then iterate through that, it'll probably perform better and be more readable. Unfortunately, get() isn't vectorised as far as I'm aware, so if you only have a string list of data frame names, you'll have to iterate through that to get a data frame list:

# build data frame list
df.list <- list()
for (i in 1:length(dfnames))
{
    df.list[[i]] <- get(dfnames[i])
}

# iterate through data frames
for (cur.df in df.list)
{
    cur.df$X <- 42:52
}

希望有帮助!