2014-04-03 48 views
0

我有一個問題構建一個循環,通過追加循環的結果給我一個表。我怎樣才能用append和loop構造一個表?

現在它正在水平添加列(變量),而不是垂直添加行。

可能追加不正確的功能?或者有沒有辦法讓它垂直追加? 也許我只是覺得我在製作一張桌子,但實際上是其他的一些結構呢?

我找到的解決方案使用rbind,但我沒有弄清楚如何使用rbind函數設置循環。

for (i in 1:3) { 
    users.humansofnewyork = append(users.humansofnewyork, getPost((humansofnewyork$id[i]) , token, n = 500, comments = TRUE,likes = TRUE, n.likes=500, n.comments=500)) 
} 

非常感謝您的回覆。不幸的是,沒有任何解決方案奏效。

這就是全碼:

#start the libaries 
library(Rfacebook) 
library(Rook) 
library(igraph) 

#browse to facebook and ask for token 
browseURL("https://developers.facebook.com/tools/explorer") 

token <- "...copy and paste token" 

#get Facebook fanpage "humansofnewyork" with post id 
humansofnewyork <- getPage("humansofnewyork", token, n=500) 

users.humansofnewyork = c() 

for (i in 1:3) { 
    users.humansofnewyork = append(users.humansofnewyork, getPost((humansofnewyork$id[i]) , token, n = 500, comments = TRUE,likes = TRUE, n.likes=500, n.comments=500)) 
} 

回答

1

append是載體。您應該使用cbind,這是rbind的列式兄弟。 (我複製你的代碼;沒有成功的承諾,如果getPost不會每次調用返回相同長度的矢量)

for (i in 1:3) { 
    users.humansofnewyork = cbind(users.humansofnewyork, getPost((humansofnewyork$id[i]) , token, n = 500, comments = TRUE,likes = TRUE, n.likes=500, n.comments=500)) 
} 
0

例如你有你的數據:

data <- data.frame ("x" = "a", "y" = 1000) 
data$x <- as.character (data$x) 
data 
    x y 
1 a 1000 

而你要用一個新值的新行追加了循環

for (i in 1:3) { 
    data <- rbind (data, c (paste0 ("Obs_",i), 10^i)) 
} 

所以WIL爲您提供:

data 
     x y 
1  a 1000 
2 Obs_1 10 
3 Obs_2 100 
4 Obs_3 1000 

你只需要關心你的c()

0

引進新值的順序如果getPost結果具有相同的元素以users.humansofnewyork列,這應該工作:

for (i in 1:3) { 
    users.humansofnewyork[nrow(users.humansofnewyork) + 1, ] = getPost((humansofnewyork$id[i]) , token, n = 500, comments = TRUE,likes = TRUE, n.likes=500, n.comments=500) 
} 

或者,使用rbind

for (i in 1:3) { 
    users.humansofnewyork = rbind(users.humansofnewyork, getPost((humansofnewyork$id[i]) , token, n = 500, comments = TRUE,likes = TRUE, n.likes=500, n.comments=500)) 
} 

但是,如果任何users.humansofnewyork列的是factor,並且任何新數據都包含新的級別,您必須首先添加新的因子級別,或將這些列轉換爲character

希望這會有所幫助。如果你提供了一個可重複的例子,它會幫助我們。