![](/img/trans.png)
[英]Summarize and count unique values of a column based on the values of another column in a dataframe
[英]Count or sum the values of 2 columns based on the value of another column in the same dataframe
我有以下數據框:
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)
我相信現在我做對了。
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
由於您使用的是邏輯,我認為使用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
一種可能性是預處理您要如何處理“重量”。 本質上,您希望添加2002的權重,而其他年份的權重則增加1。 您可以首先執行以下操作:
YG <- YG %>% add_column(wt = ifelse(year == 2002, weight, 1))
然后,您可以聚合並使用data.table
包中的dcast
函數重新排列結果。
YG %>% group_by(year, gender) %>% summarise(count = sum(wt)) %>%
dcast(formula = year~gender,fun.aggregate = sum,value.var = "count")
year F M
1 2000 1.0 2.0
2 2001 0.0 1.0
3 2002 0.7 0.9
給定您的數據,您可以使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.