-1

I have a data frame such as data

data = data.frame(ID = as.factor(c("A", "A", "B","B","C","C")),
                  var.color= as.factor(c("red", "blue", "green", "red", "green", "yellow")))

I wonder whether it is possible to get the levels of each group in ID (e.g. A, B, C) and create a variable that pastes them. I have attempted to do so by running the following:

data  %>% group_by(ID) %>%
  mutate(ex = paste(droplevels(var.color), sep = "_"))

That yields:

Source: local data frame [6 x 3]
Groups: ID [3]

      ID var.color     ex
  <fctr>    <fctr>  <chr>
1      A       red    red
2      A      blue   blue
3      B       green   red
4      B       red    red
5      C     green  green
6      C    yellow yellow

However, my desired data.frame should be something like:

ID var.color     ex
  <fctr>    <fctr>  <chr>
1      A       red    red_blue
2      A      blue    red_blue
3      B       green    green_red
4      B       red    green_red
5      C     green    green_yellow
6      C    yellow    green_yellow
Arun kumar mahesh
  • 2,289
  • 2
  • 14
  • 22
Edu
  • 903
  • 6
  • 17

2 Answers2

1

Basically, you need collapse instead of sep

Instead of dropping levels , you can just paste the text together grouped by ID

library(dplyr)
data  %>% group_by(ID) %>%
         mutate(ex = paste(var.color, collapse = "_"))

#     ID     var.color     ex
#    <fctr>    <fctr>     <chr>
#1      A       red     red_blue
#2      A      blue     red_blue
#3      B     green     green_red
#4      B       red     green_red
#5      C     green     green_yellow
#6      C    yellow     green_yellow
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 1
    I have edited it. I used `collapsed` as well but it was wrongly. Thanks for clarifying. – Edu Sep 29 '16 at 08:51
1

You can do the same by using loops

for(i in unique(data$ID)){
  data$ex[data$ID==i] <- paste0(data$var.color[data$ID==i], collapse = "_")
}

> data
  ID var.color           ex
1  A       red     red_blue
2  A      blue     red_blue
3  B     green    green_red
4  B       red    green_red
5  C     green green_yellow
6  C    yellow green_yellow
Arun kumar mahesh
  • 2,289
  • 2
  • 14
  • 22