R rbind - 参数列的数量不匹配

时间:2017-01-17 18:56:03

标签: r rstudio weather rbind

如果数据集中不存在某些列名,我该如何忽略它?

我有一个来自流的天气数据列表,但我认为某些关键天气状况不存在,因此我在rbind下面出现此错误:

Error in rbind(deparse.level, ...) : 
  numbers of columns of arguments do not match 

我的代码:

weatherDf <- data.frame()

for(i in weatherData) {
    # Get the airport code.
    airport <- i$airport

    # Get the date.
    date <- as.POSIXct(as.numeric(as.character(i$timestamp))/1000, origin="1970-01-01", tz="UTC-1")

    # Get the data in dailysummary only.
    dailySummary <- i$dailysummary

    weatherDf <- rbind(weatherDf, ldply(
        list(dailySummary),
        function(x) c(airport, format(as.Date(date), "%Y-%m-%d"), x[["meanwindspdi"]], x[["meanwdird"]], x[["meantempm"]], x[["humidity"]])
    ))
}

那么如何确保数据中存在以下关键条件:

meanwindspdi
meanwdird
meantempm
humidity

如果任何没有退出,那么忽略一堆。有可能吗?

修改

weatherData的内容在jsfiddle(我不能在这里发布,因为它太长了,我不知道哪里是向R公开显示数据的最佳位置...)

编辑2:

当我尝试将数据导出到txt时出现错误:

> write.table(weatherData,"/home/teelou/Desktop/data/data.txt",sep="\t",row.names=FALSE)
Error in data.frame(date = list(pretty = "January 1, 1970", year = "1970",  : 
  arguments imply differing number of rows: 1, 0

这是什么意思?似乎数据中存在一些错误......

编辑3:

我已将.RData中的所有数据导出到我的google驱动器:

https://drive.google.com/file/d/0B_w5RSQMxtRSbjdQYWJMX3pfWXM/view?usp=sharing

如果您使用RStudio,那么您只需导入数据。

编辑4:

target_names <- c("meanwindspdi", "meanwdird", "meantempm", "humidity")

# If it has data then loop it.
if (!is.null(weatherData)) {
    # Initialize a data frame.
    weatherDf <- data.frame()

    for(i in weatherData) {
        if (!all(target_names %in% names(i)))
            next

        # Get the airport code.
        airport <- i$airport

        # Get the date.
        date <- as.POSIXct(as.numeric(as.character(i$timestamp))/1000, origin="1970-01-01", tz="UTC-1")

        # Get the data in dailysummary only.
        dailySummary <- i$dailysummary

        weatherDf <- rbind(weatherDf, ldply(
            list(dailySummary),
            function(x) c(airport, format(as.Date(date), "%Y-%m-%d"), x[["meanwindspdi"]], x[["meanwdird"]], x[["meantempm"]], x[["humidity"]])
        ))
    }

    # Rename column names.
    colnames(weatherDf) <- c("airport", "key_date", "ws", "wd", "tempi", 'humidity')

    # Convert certain columns weatherDf type to numberic.
    columns <-c("ws", "wd", "tempi", "humidity")
    weatherDf[, columns] <- lapply(columns, function(x) as.numeric(weatherDf[[x]]))
}

检查weatherDf

> View(weatherDf)
Error in .subset2(x, i, exact = exact) : subscript out of bounds

1 个答案:

答案 0 :(得分:1)

您可以使用next跳过循环的当前迭代并转到下一次迭代:

target_names <- c("meanwindspdi", "meanwdird", "meantempm", "humidity")

for(i in weatherData) {
  if (!all(target_names %in% names(i)))
    next
  # continue with loop...