Home > Back-end >  How to observe multiple names that comes in a factor with R?
How to observe multiple names that comes in a factor with R?

Time:08-30

I have a data with a character and group:

x <- sample(LETTERS, 10)
y <- c("A","A","A","B","B","B","C","B","C","C")

df <- data.frame(x,y)
df$y <- as.factor(df$y)

How can I see what value (x) are inside each group? I tried

df %>% group_by(y)

but it is not the way I hoped.

I was hoping to get something out like this:

A : O C Z
B : N D I V 
C : R W G

Thank you

CodePudding user response:

Base R

aggregate(x~y,data=df,paste)

  y          x
1 A    A, M, S
2 B L, Q, F, Z
3 C    U, H, V

CodePudding user response:

It sounds like you may be looking for split

lapply(split(df, df$y), function(x) x$x)
#> $A
#> [1] "M" "U" "F"
#> 
#> $B
#> [1] "Q" "I" "G" "R"
#>
#> $C
#> [1] "S" "P" "K"

CodePudding user response:

dplyr option with summarise and paste like this:

x <- sample(LETTERS, 10)
y <- c("A","A","A","B","B","B","C","B","C","C")

df <- data.frame(x,y)
df$y <- as.factor(df$y)

library(dplyr)
df %>%
  group_by(y) %>%
  summarise(unique = paste(x, collapse = " "))
#> # A tibble: 3 × 2
#>   y     unique 
#>   <fct> <chr>  
#> 1 A     I U E  
#> 2 B     B T S R
#> 3 C     V L J

Created on 2022-08-29 with reprex v2.0.2

  •  Tags:  
  • r
  • Related