根据同一数据框中另一列的值对2列的值进行计数或求和

时间:2018-12-18 16:34:02

标签: r

我的数据框如下:

year<-c("2000","2000","2001","2002","2000","2002")
gender<-c("M","F","M","F","M","M")
weight<-c(0.5,0.7,0.8,0.7,0.6,0.9)
YG<-data.frame(year,gender,weight)

我想对2000和2001年的gender进行计数,并对2002年的weight求和,以创建一个新的数据框,例如:

year   M   F
1 2000 2.0 1.0
2 2001 1.0 0.0
3 2002 0.9 0.7

我尝试过类似的事情:

library(tidyverse)
YG %>%
  group_by(year) %>%
  summarise(sum(weight[year=="2002"]))%>%
  count(round(gender[year!="2002"])) %>%
  spread(gender, n, fill = 0)

4 个答案:

答案 0 :(得分:2)

我相信现在我做对了。

library(tidyverse)

YG %>%
  group_by(year, gender) %>%
  summarise(n = sum(weight),
            g = n()) %>%
  mutate(n = ifelse(year == 2002, n, g)) %>%
  select(-g) %>%
  spread(gender, n, fill = 0)
## A tibble: 3 x 3
## Groups:   year [3]
#  year      F     M
#  <fct> <dbl> <dbl>
#1 2000    1     2  
#2 2001    0     1  
#3 2002    0.7   0.9

答案 1 :(得分:2)

由于您使用的是逻辑,我认为使用case_when()会很好用。如果您在总结之前设置了逻辑,那么您要做的就是将两列相加:

library(tidyverse)
library(data.table)
YG %>% 
  mutate(Male = case_when(gender == 'F' ~ 0,
                          year %in% c('2000', '2001') & gender == 'M'~1,
                          TRUE~weight),
         Female = case_when(gender == 'M' ~ 0,
                            year %in% c('2000', '2001') & gender == 'F'~1,
                            TRUE~weight)) %>%
  group_by(year) %>%
  summarize(M = sum(Male),
            F = sum(Female))

这将为您提供所需的内容:

  year   M   F
1 2000 2.0 1.0
2 2001 1.0 0.0
3 2002 0.9 0.7

答案 2 :(得分:1)

一种可能性是预处理您要如何处理“体重”。本质上,您希望添加2002的权重,而其他年份的权重则增加1。您可以先这样做:

    lastlog | grep logged | awk '{print $1}'

然后,您可以汇总并使用YG <- YG %>% add_column(wt = ifelse(year == 2002, weight, 1)) 包中的dcast函数来重新排列结果。

data.table

答案 3 :(得分:0)

鉴于您可以使用dcast的数据:

library(data.table)
setDT(YG)
result <- dcast(YG,  year ~ gender, value.var = 'weight', fun = list(sum, length))
result[, .(year, 
           `F` = c(result$weight_length_F[1:2], result$weight_sum_F[3]),
           M = c(result$weight_length_M[1:2], result$weight_sum_M[3]))]

#year   F   M
#1: 2000 1.0 2.0
#2: 2001 0.0 1.0
#3: 2002 0.7 0.9

或者,您可以按年份在子集的数据集上两次调用dcast,如下所示:

result2 <- rbindlist(list(
      dcast(YG[year != 2002], year ~ gender, value.var = 'weight', fun = length),
      dcast(YG[year == 2002], year ~ gender, value.var = 'weight', fun = sum)))

#   year   F   M
#1: 2000 1.0 2.0
#2: 2001 0.0 1.0
#3: 2002 0.7 0.9