Reputation: 7730
Here my dataframe:
mydf <- data.frame('col_1' = c('a', 'b', 'c', 'd'), 'col_2' = c(1,1,2,2))
I would like to convert it to the following dataframe:
mydf_1 <- data.frame('col_1' = c('a', 'b', 'c', 'd'), 'col_2' = c(1,1,2,2), 'col_1' = c('a-b', 'a-b', 'c-d', 'c-d'))
so basically grouping by col_2
and converting column into string
Here is what I tried:
library(dplyr)
mydf_1 <- mydf %>% group_by(col_1) %>%
mutate(col_3 = paste(col_1, sep = "-"))
But it did not work. Any suggestions?
Upvotes: 1
Views: 1569
Reputation: 4378
Using dplyr - this makes the clear assumption there are always pairs
result <- mydf %>%
group_by(col_2) %>%
mutate(col_1.1 = if_else(is.na(lag(col_1)),
paste(col_1, lead(col_1), sep= "-"),
paste(lag(col_1), col_1, sep="-")))
# col_1 col_2 col_1.1
# <fctr> <dbl> <chr>
# 1 a 1 a-b
# 2 b 1 a-b
# 3 c 2 c-d
# 4 d 2 c-d
Upvotes: 1
Reputation: 9313
Here you go:
df$col_3 = ave(as.character(df$col_1),
df$col_2,
FUN = function(x){
paste0(x,collapse = "-")
})
This returns:
> df
col_1 col_2 col3
1 a 1 a-b
2 b 1 a-b
3 c 2 c-d
4 d 2 c-d
Upvotes: 3