0

I would like to create a column in my R data frame based on the order in which multiple values occur in one column.

For example, my data frame has an id column and an item type column, and the values of the order column is what I would like to add. Is there a way to tell R to look at the order of values in the item column so that it can spit out "ABCD" or "ADCB" (any other order) as the cell value under the 3rd column?

| id | item | order |

| 11 | A | ABCD |

| 11 | A | ABCD |

| 11 | B | ABCD |

| 11 | B | ABCD |

| 11 | C | ABCD |

| 11 | C | ABCD |

| 11 | D | ABCD |

| 11 | D | ABCD |

| 12 | A | ADCB |

| 12 | A | ADCB |

| 12 | D | ADCB |

| 12 | D | ADCB |

| 12 | C | ADCB |

| 12 | C | ADCB |

| 12 | B | ADCB |

| 12 | B | ADCB |

...

  • Try `library(dplyr);df1 %>% group_by(id) %>% mutate(order = str_c(unique(item), collapse=""))` – akrun Apr 13 '21 at 22:14
  • 1
    Thank you! I also needed to load library(stringr) since the function str_c() is from there but it outputted what I needed. – mabluan Apr 13 '21 at 22:30
  • in that case, you could use base R `transform(df, order = ave(item, id, FUN = function(x)paste0(unique(x), collapse = "")))` – Onyambu Apr 14 '21 at 01:17

0 Answers0