dplyr - Create a new column that displays multi column matches in R -
i want make new column, factors column 'a' have 1 match (value == 1) column 'b' assigned true.
a <- c(555, 555, 555, 666, 666, 666, 777, 777) b <- c(1, 0, 0, 0, 0, 0, 1, 0) df <- data.frame(a, b)
the result want is
b c 1 555 1 1 2 555 0 1 3 555 0 1 4 666 0 0 5 666 0 0 6 666 0 0 7 777 1 1 8 777 0 1
thanks in advance,
we can use dplyr
package.
library(dplyr) df2 <- df %>% group_by(a) %>% mutate(c = max(b)) df2 # tibble: 8 x 3 # groups: [3] b c <dbl> <dbl> <dbl> 1 555 1 1 2 555 0 1 3 555 0 1 4 666 0 0 5 666 0 0 6 666 0 0 7 777 1 1 8 777 0 1
or data.table
package.
library(data.table) dt <- as.data.table(df) dt2 <- dt[, c := max(b), = a] dt2 b c 1: 555 1 1 2: 555 0 1 3: 555 0 1 4: 666 0 0 5: 666 0 0 6: 666 0 0 7: 777 1 1 8: 777 0 1
Comments
Post a Comment