【问题标题】:replace values in a column based on another column but following the numeric index from the first replacement基于另一列替换列中的值,但遵循第一次替换的数字索引
【发布时间】:2016-04-18 11:11:18
【问题描述】:

我有一个看起来像上面那个的 data.frame。我需要根据第二列的值替换第一列中的值,但是替换需要继续第 1 列的数值,并且仅在 !ValB==A 时替换第 1 列中的值

>df1
ValA   ValB
   1      A
   1      A  
   2      A
   2      A
   3      A
   3      A
   4      A
   4      A
   1      B
   1      B
   1      B  
   2      B
   2      B
   3      B
   4      B
   4      B
   1      C
   1      C  
   2      C
   2      C
   3      C
   3      C
   4      C
   1      C

我想要的是替换 column1 中的值,但使用 ValB==B 作为替换 ValA 中的值的索引。替换必须继续ValA 中的值,即当有1ValB==B 时,ValA 必须是52 必须是6 等等.请在这里是所需的输出,这将使我更容易理解我在做什么。我可以用 ifelseif 语句做一个 for 循环,但我确信有一种更清洁的方法,

期望的输出

>df1
ValA   ValB
   1      A
   1      A  
   2      A
   2      A
   3      A
   3      A
   4      A
   4      A
   5      B
   5      B
   5      B  
   6      B
   6      B
   6      B
   7      B
   7      B
   8      C
   8      C  
   9      C
   9      C
  10      C
  10      C
  11      C
  12      C

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    你可以做这样的事情。它基本上在一个布尔向量上运行一个累积和,它告诉你一行的 ValA 和 ValB 是否等于前一行的 -

    # do a running sum of the values
    df$c = cumsum(
       c(
       # first value of the result is the same value as the first value of A
       df$ValA[1],
       # go through the second to the last value of the vector and compared it to the first to the n - 1th values
       sapply(
          2:nrow(df),
          function(index) {
    
             # look for change in value of A and B both
             # if changed then return 1, else return 0
             !(
                df$ValA[index] == df$ValA[index - 1] & 
                   df$ValB[index] == df$ValB[index - 1]
             )
    
          }
       )
    ))
    

    【讨论】:

    • 与标题所暗示的不同,它似乎并没有与描述中的上一行相关联,而是更多地与第二列级别的“排名”相关联。
    • 谢谢@TheComeOnMan,你的方法行得通,你能解释一下吗?
    • 我添加了 cmets。如果你从内到外跟随他们,你应该能够跟随正在发生的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    相关资源
    最近更新 更多