2016-06-11 43 views
-1

我想用兩列製作一個data.frame。與微博的ID的第一和第二列中的信息取決於鳴叫是否是回覆或轉推data.frame與twitter數據

id_str | x$retweeted_status$id_str or x$in_reply_to_status_id_str 

我可以做一個數據幀有三列布埃我需要兩個。

我的代碼:

ids <- sapply(tweets.list, function(x) x$id_str) 
    ret_ids <- sapply(tweets.list, function(x) if(is.null(x$retweeted_status)) NA else x$retweeted_status$id_str) 
    rep_ids <- sapply(tweets.list, function(x) if(is.null(x$in_reply_to_status_id_str)) NA else x$in_reply_to_status_id_str) 
    isnt.null <- function(x)!is.null(x) 
r_ids <- sapply(tweets.list, function(x) if(is.null(x$retweeted_status)) x$in_reply_to_status_id_str else x$retweeted_status$id_str) 
data.frame(ids,r_ids) 

輸出:

Error in data.frame("733222936912351232", NULL, "733220677721968641", : 
    arguments imply differing number of rows: 1, 0 

數據:

ids|ret_ids|rep_ids 
1|40|NA 
2|32|NA 
3|NA|555 
4|NA|444 

結果期望:

ids|r 
1|40 
2|32 
3|555 
4|444 
+0

請添加一些數據,使其[重複的例子(http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610) – alistaire

+0

完成。謝謝。 –

+0

您仍然沒有任何實際讓代碼運行的數據。如果你只是想將三列分成兩列,data.frame(ids = df [,1],r = rowSums(df [, - 1],na.rm = T))''。 – alistaire

回答

0

這裏有一種方法

df <- read.table(header=T, sep="|", text="ids|ret_ids|rep_ids 
1|40|NA 
2|32|NA 
3|NA|555 
4|NA|444") 

setNames(as.data.frame(t(apply(df, 1, na.omit))), c("ids", "r")) 
# ids r 
# 1 1 40 
# 2 2 32 
# 3 3 555 
# 4 4 444 
相關問題