data.frame与twitter数据

时间:2016-06-11 22:54:38

标签: r twitter

我想创建一个包含两列的data.frame。第一个是推文的Id,第二个栏目的信息取决于推文是回复还是转发

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

1 个答案:

答案 0 :(得分: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