R:计算新的可变R代码

时间:2018-06-27 18:23:33

标签: r dataframe

我有

            id_1 id_2  name  count total
          1  001  111    a     15  
          2  001  111    b      3   
          3  001  111   sum    28   28
          4  002  111    a      7  
          5  002  111    b     33
          6  002  111   sum    48   48

我希望共享id_1和id_2的行共享总数,例如

            id_1 id_2  name   count total
          1  001  111    a     15   28
          2  001  111    b      3   28
          3  001  111   sum    28   28
          4  002  111    a      7   48
          5  002  111    b     33   48
          6  002  111   sum    48   48

4 个答案:

答案 0 :(得分:3)

我们可以使用lst1, lst2 = (sorted(i, key=lambda x: x['name']) for i in [lst1, lst2]) 中的fill

tidyr

数据

library(tidyr)

dat2 <- dat %>% fill(total, .direction = "up")
dat2
#   id_1 id_2 name count total
# 1    1  111    a    15    28
# 2    1  111    b     3    28
# 3    1  111  sum    28    28
# 4    2  111    a     7    48
# 5    2  111    b    33    48
# 6    2  111  sum    48    48

答案 1 :(得分:1)

考虑基础R的ave计算组max na.rm 处理NA):

df$total <- ave(df$total, df$id_1, df$_id_2, FUN=function(i) max(i, na.rm=na.omit))

df
#   id_1 id_2 name count total
# 1    1  111    a    15    28
# 2    1  111    b     3    28
# 3    1  111  sum    28    28
# 4    2  111    a     7    48
# 5    2  111    b    33    48
# 6    2  111  sum    48    48

答案 2 :(得分:1)

使用zoodata.table

df <- read.table(text = "id_1 id_2  name  count total
            001  111    a     15  NA
                    001  111    b      3   NA
                    001  111   sum    28   28
                    002  111    a      7  NA
                    002  111    b     33   NA
                    002  111   sum    48   48",
                  header = TRUE, stringsAsFactors = FALSE)# create data
library(zoo)# load packages
library(data.table)
setDT(df)[, total := na.locf(na.locf(total, na.rm=FALSE), na.rm=FALSE, fromLast=TRUE), by = c("id_1", "id_2")]# convert df to data.table and carry forward and backward total by ids

输出:

    id_1 id_2 name count total
1:    1  111    a    15    28
2:    1  111    b     3    28
3:    1  111  sum    28    28
4:    2  111    a     7    48
5:    2  111    b    33    48
6:    2  111  sum    48    48

答案 3 :(得分:1)

使用常规dplyr方法的简单方法:

dat %>% group_by(id_1, id_2) %>% mutate(total=count[name == "sum"])

或者:

dat %>% group_by(id_1, id_2) %>% mutate(total=na.omit(total)[1])

   id_1  id_2 name  count total
  <int> <int> <chr> <int> <int>
1     1   111 a        15    28
2     1   111 b         3    28
3     1   111 sum      28    28
4     2   111 a         7    48
5     2   111 b        33    48
6     2   111 sum      48    48