-1

I have a 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))

I want to have a df like this

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))

Could anyone help me, please? Thank you

Liselotte
  • 382
  • 1
  • 8

1 Answers1

1

A solution using dplyr. The idea is group_by col1 and calculate sum for all the other columns.

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
www
  • 38,575
  • 12
  • 48
  • 84