将变换应用于多个data.frame对象

将变换应用于多个data.frame对象,r,dataframe,R,Dataframe,我想对一些data.frame对象应用转换。我该怎么做?我在想我可以通过某种方式在这些物体中循环,但到目前为止这是徒劳的。我想我可能需要将对data.frame对象的引用传递给列表或其他类型的集合,然后循环遍历这些引用。这在R中可能吗 #reproducible data foo=data.frame(c(1, 1), c(1, 1)) bar=data.frame(c(2, 2), c(2, 2)) #apply transformations for (dat in list(foo, ba

我想对一些data.frame对象应用转换。我该怎么做?我在想我可以通过某种方式在这些物体中循环,但到目前为止这是徒劳的。我想我可能需要将对data.frame对象的引用传递给列表或其他类型的集合,然后循环遍历这些引用。这在R中可能吗

#reproducible data
foo=data.frame(c(1, 1), c(1, 1))
bar=data.frame(c(2, 2), c(2, 2))
#apply transformations
for (dat in list(foo, bar)){
    dat$NEW <- 9999
    print(dat)
}
#of course nothing happened since data.frames were copied to list object
print(foo) #no change
print(bar) #no change

#expected output
foo$NEW <- 9999
bar$NEW <- 9999
print(foo) #looks good 
print(bar) #looks good
#可复制数据
foo=data.frame(c(1,1),c(1,1))
bar=数据帧(c(2,2),c(2,2))
#应用变换
用于(列表中的数据(foo,bar)){

dat$NEW您可以这样做,并继续使用data.frames列表

foo=data.frame(a = c(1, 1), b = c(1, 1))
bar=data.frame(a = c(2, 2), b = c(2, 2))

dat <- list(foo = foo, bar = bar)
dat <- lapply(dat, function(x){
  x$NEW = 999
  x
})
如果要强制
foo
dat$foo
相同,可以使用

mapply(assign, names(dat), dat, MoreArgs = list(envir = .GlobalEnv))
导致

> foo
  a b NEW
1 1 1 999
2 1 1 999

bar也一样

不清楚您想做什么。可能会添加预期的输出?我希望
print(foo)
print(bar)
的返回值与
print(dat)的返回值相同
来自循环语句。这太棒了!与其他语言相比仍然有些尴尬。顺便说一句,可以使用
list2env(dat,globalenv())而不是
mappy
> foo
  a b NEW
1 1 1 999
2 1 1 999