1

For example I have a data frame...

pet_data <- data.frame(
   pet = c("dog", "cat", "monkey"), 
   name = c("fido", "garfield", "george"), 
   color = c("black", "orange", "brown")
)

...and I want a fourth column that at each row contains a list of the other values in that row. So the first entry in the fourth column would be a list containing "dog", "fido", and "black", the second entry in the column would be a list containing "cat", "garfield", "orange", etc.

Thanks!

1 Answers1

4

You can split the data rowwise using asplit and add it as a new column.

pet_data$new_col <- asplit(pet_data, 1)
pet_data

#     pet     name  color               new_col
#1    dog     fido  black      dog, fido, black
#2    cat garfield orange cat, garfield, orange
#3 monkey   george  brown monkey, george, brown

pet_data$new_col
#[[1]]
#    pet    name   color 
#  "dog"  "fido" "black" 

#[[2]]
#       pet       name      color 
#     "cat" "garfield"   "orange" 

#[[3]]
#     pet     name    color 
#"monkey" "george"  "brown" 

In dplyr we can use rowwise -

library(dplyr)

pet_data %>%
  rowwise() %>%
  mutate(new_col = list(c_across())) %>%
  ungroup

#   pet    name     color  new_col  
#  <chr>  <chr>    <chr>  <list>   
#1 dog    fido     black  <chr [3]>
#2 cat    garfield orange <chr [3]>
#3 monkey george   brown  <chr [3]> 
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213