Reputation: 1
I want to make a new column, where factors from column 'a' that have one match (value == 1) with column 'b' are assigned by 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 i want is
a 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,
Upvotes: 0
Views: 68
Reputation: 887173
We can use base R
split
df$c <- unsplit(lapply(split(df$b, df$a), max), df$a)
df$c
#[1] 1 1 1 0 0 0 1 1
Upvotes: 1
Reputation: 39154
We can use the dplyr
package.
library(dplyr)
df2 <- df %>%
group_by(a) %>%
mutate(c = max(b))
df2
# A tibble: 8 x 3
# Groups: a [3]
a 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 the data.table
package.
library(data.table)
dt <- as.data.table(df)
dt2 <- dt[, c := max(b), by = a]
dt2
a 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
Upvotes: 2