【发布时间】:2016-06-03 19:51:04
【问题描述】:
我正在尝试提取一些网络数据并将其放入数据框中以供将来使用。某些列中的某些值是 NA;我希望这些单元格有 NA 或一些文本。这是我正在使用的 for 循环:
extra <- as.data.frame(matrix(NA, nrow = length(main.node), ncol = 2))
for (i in 1:length(main.node)){
extra[i,1] <- main.node[[i]]$data$author
extra[i,2] <- main.node[[i]]$data$author_flair_text
}
问题是author_flair_text 的某些值不存在(作者列工作正常)。例如,调用
main.node[[4]]$data$author_flair_text 返回NULL。
我收到了错误
Error in `[<-.data.frame`(`*tmp*`, i, 2, value = NULL) :
replacement has length zero
基本上,我需要 for 循环来填写缺失的信息。有没有办法在 for 循环中将 NULL 转换为“NULL”?
如果这有帮助,这里是 main.node 的来源:
raw_data = tryCatch(RJSONIO::fromJSON(readLines(URL, warn = FALSE)),
error = function(e) NULL)
main.node = raw_data[[2]]$data$children
谢谢!!
【问题讨论】:
-
使用
if语句,使用is.null判断值是否为NULL
标签: r for-loop dataframe web-scraping