【问题标题】:Replacing NA in column with values in adjacent column用相邻列中的值替换列中的 NA
【发布时间】:2017-04-22 22:25:51
【问题描述】:

我有一个这样的数据框:

  A       B        C       D       E       F        G        H
  a     LOW      1.5     0.2      NA    1000     2000       NA
  b     LOW      2.9     0.4    HIGH    6000     1000       NA
  c     LOW        1     1.3     LOW     400     1111      LOW 
  d     LOW        2      10     LOW    1000      400     HIGH

如何执行条件语句来替换 NA 值。

对于E列,我想取C列和D列的差,小于0显示“小幅减少”,大于0则显示“小幅增加”。

然后对于H列,除了使用F列和G列的差异之外,做同样的事情。如果低于0则显示“小幅减少”,如果高于0则显示“小幅增加”。

最终输出应如下所示:

  A       B        C       D                 E       F        G                    H
  a     LOW      1.5     0.2    Small Increase    1000     2000       Small Decrease
  b     LOW      2.9     0.4              HIGH    6000     1000       Small Increase
  c     LOW        1     1.3               LOW     400     1111                  LOW 
  d     LOW        2      10               LOW    1000      400                 HIGH

【问题讨论】:

    标签: r conditional na


    【解决方案1】:

    对其他列也执行类似的步骤!

    df$E <- ifelse(is.na(df$E), ifelse(df$C-df$D <0,"small decrease","small increase"), df$E)
    

    【讨论】:

      【解决方案2】:

      这是一个使用来自data.tableset 的选项,因为它可以在适当的位置分配值,所以非常有效

      library(data.table)
      setDT(df1)#converts 'data.frame' to 'data.table'
      #loop through the index of the concerned columns
      for(j in c(5L, 8L)) {
        #get the row index of NA for each column
        i1 <- which(is.na(df1[[j]])) 
        #get the value to be replaced based on the difference
        val <- c("Small Increase", "Small Decrease")[((df1[[j-2]][i1] - df1[[j-1]][i1]) < 0) + 1]
        #set the NA elements to the above val
        set(df1, i = i1, j = j, value = val)
       }
      
      df1
      #   A   B   C    D              E    F    G              H
      #1: a LOW 1.5  0.2 Small Increase 1000 2000 Small Decrease
      #2: b LOW 2.9  0.4           HIGH 6000 1000 Small Increase
      #3: c LOW 1.0  1.3            LOW  400 1111            LOW
      #4: d LOW 2.0 10.0            LOW 1000  400           HIGH
      

      数据

      df1 <- structure(list(A = c("a", "b", "c", "d"), B = c("LOW", "LOW", 
      "LOW", "LOW"), C = c(1.5, 2.9, 1, 2), D = c(0.2, 0.4, 1.3, 10
      ), E = c(NA, "HIGH", "LOW", "LOW"), F = c(1000L, 6000L, 400L, 
      1000L), G = c(2000L, 1000L, 1111L, 400L), H = c(NA, NA, "LOW", 
      "HIGH")), .Names = c("A", "B", "C", "D", "E", "F", "G", "H"), 
      class = "data.frame", row.names = c(NA, -4L))
      

      【讨论】:

        猜你喜欢
        • 2015-07-28
        • 1970-01-01
        • 2013-03-15
        • 1970-01-01
        • 2021-09-22
        • 2012-11-10
        • 2016-02-07
        • 1970-01-01
        相关资源
        最近更新 更多