简体   繁体   中英

Turn column into string in R

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM