% count(round(gender[-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:09:45 27 4
gpt4 key购买 nike

我有下面的数据框:

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 年的性别,并对 2002 年的权重求和,以便创建一个新的数据框,例如:

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

关于r - 根据同一数据框中另一列的值对 2 列的值进行计数或求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53837408/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com