R - 循环中几个数据帧的新变量 [英] R - New variables over several data frames in a loop
问题描述
所有数据帧都相同名称结构,所以我正在用它来循环使用它们。这里是一些伪代码,我想要做的是
Name = Dataframe_1 #Assume for循环从Dataframe_1到_10 (循环未显示)
#伪代码
eval(as.name(Name))$ NewVariable < - c(SomeString)#这是我想要做的,但是我收到一个错误(找不到函数eval< - )
我应该有一个额外的列(NewVariable)相同的数据框,其中所有行的值为$ code>SomeString。
如果我使用 eval(as.name(Name))
我可以调用数据框名称
没有问题,但没有一个通常的数据帧运算符似乎与该特定调用(不是 - - 赋值,或$或[[]])
任何想法将不胜感激,谢谢提前!
我们可以将数据集放在列表
,并通过循环列表
与 lapply $ c创建一个新列$ c>。如果需要,可以使用
list2env
更新原始数据框对象。
lst< - mget(paste0('Dataframe_',1:10))
lst1< - lapply(lst,transform,NewVariable =SomeString)
list2env(lst1,envir = .GlobalEnv )
或另一个选项是与 assign
nm1 < - ls(pattern =^ Dataframe_\\d +)
nm2 < rep(NewVariable,length(nm1))
for(j in seq_along(nm1)){
assign(nm1 [j],`[< -`(get(nm1 [j]) ,nm2 [j],value =SomeString))
}
In R, I have several datasets, and I want to use a loop to create new variables (columns) within each of them:
All dataframes have the same name structure, so that is what I am using to loop through them. Here is some pseudo-code with what I want to do
Name = Dataframe_1 #Assume the for-loop goes from Dataframe_1 to _10 (loop not shown)
#Pseudo-code
eval(as.name(Name))$NewVariable <- c("SomeString") #This is what I would like to do, but I get an error ("could not find function eval<-")
As a result, I should have the same dataframe with one extra column (NewVariable), where all rows have the value "SomeString"
.
If I use eval(as.name(Name))
I can call up the dataframe Name
with no problem, but none of the usual data frame operators seem to work with that particular call (not <- assignment, or $ or [[]])
Any ideas would be appreciated, thanks in advance!
We can place the datasets in a list
and create a new column by looping over the list
with lapply
. If needed, the original dataframe objects can be updated with list2env
.
lst <- mget(paste0('Dataframe_', 1:10))
lst1 <- lapply(lst, transform, NewVariable = "SomeString")
list2env(lst1, envir = .GlobalEnv())
Or another option is with assign
nm1 <- ls(pattern = "^Dataframe_\\d+")
nm2 <- rep("NewVariable", length(nm1))
for(j in seq_along(nm1)){
assign(nm1[j], `[<-`(get(nm1[j]), nm2[j], value = "SomeString"))
}
这篇关于R - 循环中几个数据帧的新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!