R中

R中

问题描述:

循环通过Twitter追随者rtweet包我有一个使用特定主题标签,现在我想做一个网络图,看看他们遵循谁的Twitter ID的列表。随着全新rtweet包,想法是,每个user_id我使用get_friends函数,并最终与两列表 - userids | 以下R中

的问题是,而不是两列,我最终只有一个。下面是基于类似的问题,我在做什么:

#this is where the ids list comes from 
head(ids) 
user_id    freq 
2953382183   291 
2832407758   178 
522476436   149 
773707421579677696 117 
1296286704   113 
773555423970529280 113 

#for each user_id, get_friends() show me who the user is following 
userids <- ids[1,1] 
following <- get_friends(userids) 
head(following) 
       ids 
     540219772 
757699150507020288 
     2392165598 
     628569910 
     576547113 
     181996651 

#NOW I'LL TRY TO FILL A NEW DATA FRAME FOR EACH "user_id" WITH ALL FOLLOWING "ids" 

#initializing an empty data frame 
final <- data.frame(userids = character(), following =character()) 

totalusers <- nrow(ids) #ids is a data frame where I got all `user_id` 
userids <- NULL 
following <- NULL 
df <- NULL 

for (i in 1:totalusers) 
{ 
userids[i] <- ids[i,1] 
following <- get_friends(userids[i]) #get_friends returns a data frame, by package default 
df[i] <- data.frame(userids[i], following) 
final <- rbind(final, df[i]) 
} 

有谁知道我怎么追加以下变量,这个数据帧?非常感谢。

+1

您可能应该阅读增长对象上的RInferno。你想要做的是索引正确的行和列,而不是在每次迭代中创建数据帧,或者类似地,在每次迭代中使用'rbind'。 – shayaa

+0

非常感谢@shayaa。现在我将用一个使用数据框的解决方案来编辑​​帖子,而我正在以更高效的方式来完成此任务。 –

+0

没问题。提供一个用于测试代码的最小数据集以及预期结果是公认的标准。如果你不这样做,你经常会陷入低谷。此外,您可以将解决方案发布到自己的问题上,您不需要将其作为编辑。 – shayaa

对于一个给定的id的(ids),你可以做到以下几点:

library(rtweet) 
library(plyr) 
ids<-c("156562085","808676983","847366544183050240")#the users id 
list_of_friends<-lapply(ids,get_friends)#get all the friends' ids per each user id 
names(list_of_friends)<-ids 
list_of_friends2<-lapply(list_of_friends,function(y) dim(y)[1])#get the number of friends 
df1<-ldply(list_of_friends2, data.frame)#transform the data into data.frame 
names(df1)<-c("user_id","following") 

df1产量:

   user_id   following 
1   156562085   339 
2   808676983   1066 
3 847366544183050240    0 

Additio应受为了产生edge list

f1<-function(x){ 
    return(cbind(rep(names(list_of_friends[x]),dim(list_of_friends[[x]]) 
[1]),list_of_friends[[x]])) 
} 
l1<-lapply(names(list_of_friends),f1) 
df2<-ldply(l1,data.frame) 
names(df2)<-c("user_id","friend_id") 

产生df2

user_id   friend_id 
1 156562085   26787673 
2 156562085   18139619 
3 156562085   23827692 
       [...] 
1403 808676983   19397785 
1404 808676983   50393960 
1405 808676983   113419517 

如果从followingdf1添加列值,你会得到1405,同意nrow(df2)。我相信df2是你想要的第一个地方。

下面这段代码的作品,但也许它不是为大型数据集的最有效方式。

for (i in 1:totalusers) 
{ 
userids[i] <- ids[i,1] 
following <- get_friends(userids[i]) 
final <- rbind(final, data.frame(userids=userids[i], following=following)) 
} 

我结束了与此:

userids     ids 
2953382183   540219772 
2953382183 757699150507020288 
2953382183   2392165598 
2953382183   628569910 
2953382183   576547113 
2953382183   181996651