【问题标题】:replacement length zero R替换长度为零 R
【发布时间】: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


【解决方案1】:

试试这个。警告我没有运行它,我只是写了它,所以可能有错字:

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
  temp <- main.node[[i]]$data$author_flair_text
  if(is.null(temp)){
    temp <- "NULL"
  }
  extra[i,2] <- temp
}

【讨论】:

    【解决方案2】:

    您可以在此处使用ifelse() 构造。它有一个test 参数(用于条件)、一个yes 参数(测试为真时的值)和no 参数(测试为假时的值)。

    在你的情况下,它看起来像这样:

    temp <- main.node[[i]]$data$author_flair_text
    extra[i,2] <- ifelse(is.null(temp), "your_null_indicator", temp)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多