按多列

时间:2017-07-06 14:54:48

标签: r data.table dplyr plyr

我有很多数据记录要按列名分组。

Name  Surname  value
al     adams    120
al     adams    514
al     bats     220
al     bats     120
bill   cox      440
bill   cox      320
bill   brit     320

我希望按名称和姓氏进行分组(并保留它们),并使用值的总和。 这是我的代码。我没有得到想要的显示。

DT<-base_AA_P1 %>%  select(Name, Surname) %>% group_by(Name, Surname) %>%  summarize(SUM_value = sum(value, na.rm = TRUE))

1 个答案:

答案 0 :(得分:0)

试试这个:

data = data.frame(Name = c("al","al","al","al","bill","bill","bill"),
                  Surname = c("adams","adams","bats","bats","cox","cox","brit"),
                  value = c(120,514,220,120,440,320,320))


library(dplyr)

data2 = data %>%
  group_by(Name,Surname)%>%
  summarise(new_value = sum(value))

data2

    Name Surname new_value
1     al   adams       634
2     al    bats       340
3   bill    brit       320
4   bill     cox       760

我认为,如果您选择名称和姓氏,您将无法获得所需的最终数据中的值总和。