Home > front end >  How do I display multiple values in an R data table cell?
How do I display multiple values in an R data table cell?

Time:10-19

I have an R dataframe with ages and scores. I need to create a table to display unique scores as column names and unique ages as rows, with associated names in the cells, as shown below. Whats the best approach to achieve this?

Name <- c("Jon", "Bill", "Maria", "Ben", "Tina","Aaron","Phil","Liv")
Age <- c(20, 40, 30, 50, 20,40,20,30)
Score <- c("A","B","A","D","C","B","A","D")

df <- data.frame(Name, Age, Score)

enter image description here

CodePudding user response:

With pivot_wider:

library(tidyr)
library(dplyr)
df %>% 
  pivot_wider(names_from = Score, names_prefix = "Score_",
              values_from = Name, values_fn = toString, values_fill = "") %>% 
  relocate(Age, order(colnames(.)))

#   Age   Score_A     Score_B Score_C Score_D
# 1  20 Jon, Phil                Tina        
# 2  40           Bill, Aaron                
# 3  30     Maria                         Liv
# 4  50                                   Ben

CodePudding user response:

Using aggregate to combine the strings.

library(tidyr)

data.frame(aggregate(Name ~ ., df, function(x) c(unique(x))) %>% 
  pivot_wider(values_from=Name, names_from=Score, values_fill=list("")))
  Age         A           B    C   D
1  20 Jon, Phil             Tina    
2  30     Maria                  Liv
3  40           Bill, Aaron         
4  50                            Ben

CodePudding user response:

Use reshape:

reshape2::dcast(df, Age~Score, toString, value.var = 'Name')

  Age         A           B    C   D
1  20 Jon, Phil             Tina    
2  30     Maria                  Liv
3  40           Bill, Aaron         
4  50                            Ben
  • Related