问题描述
我正在寻找使用for循环创建多个数据框,然后用 merge()将它们拼接在一起。我可以使用 assign(paste(),blah)创建数据框。但是,在同一个for循环中,我需要删除每个数据框的第一列。
以下是我的代码的相关位:
$ $ $ $ $ $ $ $ $ $ $ $ {$ $ $ $ $ $ $ $ $ $ $ $'这个工作
assign(paste(platform,j,df,sep =_),read.csv(file = paste(masterfilename,extension,sep =。),header = FALSE,skip = 1,nrows = 100))
#这是删除第一列
#这是行不通的
assign(paste(platform,j,df $ V1,sep =_),NULL)
}
在第一种情况下,我的变量到一个数据框,所以他们继承了这种类型。但在第二种情况下,我将它分配给 NULL 。
有没有人对我如何解决这个问题有任何建议?另外,有没有比 assign()更优雅的解决方案,这似乎陷入了我的代码?谢谢,
可以用来创建变量名,但是name $ V1不是一个变量名。 $ 是R中的一个运算符,因此您试图构建一个函数调用,而您不能使用 assign 。事实上,在这种情况下,最好完全避免 assign 。你不需要创建一堆不同的变量。如果你的data.frames是相关的,只要把它们保存在一个列表中。
mydfs< - lapply(1:3,function(j){
df< - read.csv file = paste(masterfilename,extension,sep =。),
header = FALSE,skip = 1,nrows = 100))
df $ V1 df
$ b现在你可以用 mydfs [[1]] , mydfs [[2]] 等等。你可以用 *应用系列功能。I'm looking to create multiple data frames using a for loop and then stitch them together with merge().
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) }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.
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 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 })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:动态创建一个变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!