将值分配给前一列的列

时间:2018-03-02 22:05:18

标签: r

基本上“计数”列是天数之间的差异   从而导致所有第1天的归零。我想在计数中替换0   包含第1天数据的列。

 Sample Data 
  Unique ID   Day    Total Counts   Color  Counts
   123        Day 1       12           Red    0
   123        Day 2       14           Red    2
   123        Day 3       17           Red    3
   123        Day 4       21           Red    4
   133        Day 1       10           Red    0
   133        Day 2       14           Red    4
   133        Day 3       17           Red    3
   133        Day 4       22           Red    5
   133        Day 3       25           Red    3
   133        Day 5       30           Red    5

我想拥有什么

  Unique ID   Day    Total Counts   Color  Counts
   123        Day 1       12           Red    12
   123        Day 2       14           Red    2
   123        Day 3       17           Red    3
   123        Day 4       21           Red    4
   133        Day 1       10           Red    10
   133        Day 2       14           Red    4
   133        Day 3       17           Red    3
   133        Day 4       22           Red    5
   133        Day 3       25           Red    3
   133        Day 5       30           Red    5

1 个答案:

答案 0 :(得分:2)

df <- read.table(text = "UniqueID   Day    TotalCounts   Color  Counts
                  123       Day1       12           Red    0
                 123        Day2       14           Red    2
                 123        Day3       17           Red    3
                 123        Day4       21           Red    4
                 123        Day1       10           Red    0
                 123        Day2       14           Red    4
                 123        Day3       17           Red    3
                 123        Day4       22           Red    5
                 123        Day3       25           Red    3
                 123        Day5       30           Red    5", 
                 header = TRUE, stringsAsFactors = FALSE)

library(data.table)
setDT(df)
df[Counts == 0, Counts := TotalCounts]


    UniqueID  Day TotalCounts Color Counts
 1:      123 Day1          12   Red     12
 2:      123 Day2          14   Red      2
 3:      123 Day3          17   Red      3
 4:      123 Day4          21   Red      4
 5:      123 Day1          10   Red     10
 6:      123 Day2          14   Red      4
 7:      123 Day3          17   Red      3
 8:      123 Day4          22   Red      5
 9:      123 Day3          25   Red      3
10:      123 Day5          30   Red      5