R:动态创建变量名 [英] R: Dynamically create a variable name

查看:36
本文介绍了R:动态创建变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用 for 循环创建多个数据框,然后使用 merge() 将它们拼接在一起.

I'm looking to create multiple data frames using a for loop and then stitch them together with merge().

我可以使用 assign(paste(), blah) 创建我的数据框.但是,在同一个 for 循环中,我需要删除每个数据框的第一列.

I'm able to create my data frames using assign(paste(), blah). But then, in the same for loop, I need to delete the first column of each of these data frames.

这是我的代码的相关部分:

Here's the relevant bits of my code:

for (j in 1:3)
{
    #This is to create each data frame
    #This works
    assign(paste(platform, j, "df", sep = "_"), read.csv(file = paste(masterfilename,    extension, sep = "."), header = FALSE, skip = 1, nrows = 100))

    #This is to delete first column
    #This does not work
    assign(paste(platform, j, "df$V1", sep = "_"), NULL)
}

在第一种情况下,我将变量分配给数据框,因此它们继承了该类型.但在第二种情况下,我将其分配给 NULL.

In the first situation I'm assigning my variables to a data frame, so they inherit that type. But in the second situation, I'm assigning it to NULL.

有人对我如何解决这个问题有任何建议吗?另外,是否有比 assign() 更优雅的解决方案,这似乎使我的代码陷入困境?谢谢,

Does anyone have any suggestions on how I can work this out? Also, is there a more elegant solution than assign(), which seems to bog down my code? Thanks,

n.i.

推荐答案

assign 可用于构建变量名,但name$V1"不是变量名.$ 是 R 中的一个运算符,因此您正在尝试构建一个函数调用,而使用 assign 则无法做到这一点.事实上,在这种情况下最好完全避免 assign.您不需要创建一堆不同的变量.如果您的 data.frames 相关,只需将它们保存在列表中.

assign can be used to build variable names, but "name$V1" isn't a variable name. The $ is an operator in R so you're trying to build a function call and you can't do that with assign. In fact, in this case it's best to avoid assign completely. You con't need to create a bunch of different variables. If you data.frames are related, just keep them in a list.

mydfs <- lapply(1:3, function(j) {
    df<- read.csv(file = paste(masterfilename, extension, sep = "."), 
        header = FALSE, skip = 1, nrows = 100))
    df$V1<-NULL
    df
})

现在您可以使用 mydfs[[1]]mydfs[[2]] 等访问它们.您可以使用任何*apply 函数系列的成员.

Now you can access them with mydfs[[1]], mydfs[[2]], etc. And you can run functions overall data.sets with any of the *apply family of functions.

这篇关于R:动态创建变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆