2015-11-16 27 views
1

我想将转换应用于多个data.frame对象。我会怎么做?我想我可以通过这些物体循环,但是迄今为止这是无用的。我想我可能需要将对data.frame对象的引用传递给列表或其他类型的集合,然后遍历这些引用。这在R中甚至可能吗?将转换应用于多个data.frame对象

#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 
+0

目前还不清楚你想要做什么。也许增加预期的输出? –

+0

我希望'print(foo)'和'print(bar)'的返回值与循环语句中的'print(dat)'的返回值相同。 –

回答

1

你可以做这样的事情,并继续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 
}) 

现在DAT看起来如下工作:

$foo 
    a b NEW 
1 1 1 999 
2 1 1 999 

$bar 
    a b NEW 
1 2 2 999 
2 2 2 999 

如果要强制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

+1

太棒了!与其他语言相比,仍然有些尴尬。顺便说一句,代替'mapply'可以使用'list2env(dat,globalenv())' –