2014-04-03 47 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

希望这会有所帮助。如果你提供了一个可重复的例子,它会帮助我们。