我有一个 df
df1 <- data.frame(col1=c("x","y","y","z","z","z"), col2=c(0,1,0,0,0,1), col3=c(0,0,1,0,0,0), col4=c(1,0,0,0,1,0), col5=c(0,1,0,0,0,0))
我想要一个这样的 df
df2 <- data.frame(col1=c("x","y","z"), col2=c(0,1,1), col3=c(0,1,0),col4=c(1,0,1), col5=c(0,1,0))
请问有人可以帮我吗?谢谢
使用dplyr
. 这个想法是group_by
col1
计算所有其他列的总和。
library(dplyr)
df <- df1 %>%
group_by(col1) %>%
summarize_all(~sum(.)) %>%
ungroup()
df
# # A tibble: 3 x 5
# col1 col2 col3 col4 col5
# <chr> <dbl> <dbl> <dbl> <dbl>
# 1 x 0 0 1 0
# 2 y 1 1 0 1
# 3 z 1 0 1 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句