【问题标题】:combining values in two columns in to a single new column in R将两列中的值合并到 R 中的一个新列中
【发布时间】:2018-05-11 15:04:06
【问题描述】:

如何合并两列,使一列中的值替换另一列中的 NA?

初始数据帧

date1                         date2
2016-08-29 02:31:34            NA
NA                      2016-08-29 17:59:23

变换后的数据框

date1                         date2                     Newdate
2016-08-29 02:31:34            NA                 2016-08-29 02:31:34 
NA                      2016-08-29 17:59:23       2016-08-29 17:59:23

【问题讨论】:

    标签: r date data-transform


    【解决方案1】:

    试试dplyr::coalesce(...)

    数据 - 注意 coalesce 不适用于因子

    df <- read.table(text="date1,date2
    2016-08-29 02:31:34,NA
    NA,2016-08-29 17:59:23", header=TRUE, sep=",", stringsAsFactors=FALSE)
    

    解决方案

    df$dates <- dplyr::coalesce(df$date1, df$date2)
                    # date1               date2               dates
    # 1 2016-08-29 02:31:34                <NA> 2016-08-29 02:31:34
    # 2                <NA> 2016-08-29 17:59:23 2016-08-29 17:59:23
    

    【讨论】:

      【解决方案2】:

      试试下面的代码:

      # Simulating your data
      date1 <- c("2016-08-29 02:31:34", NA)
      date2 <- c(NA, "2016-08-29 17:59:23")
      df <- data.frame(date1, date2, stringsAsFactors = FALSE)
      
      # Actual solution
      Newdate <- df$date1 # Copy the values from date1
      Newdate[is.na(df$date1)] <- date2[is.na(df$date1)] # Replace every position where date1 is NA.
      df$Newdate <- Newdate # Create the new column
      print(df)
      

      希望对您有所帮助! :)

      【讨论】:

        猜你喜欢
        • 2019-03-10
        • 1970-01-01
        • 2012-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-19
        相关资源
        最近更新 更多