2015-11-16 25 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())' –

相關問題