简体   繁体   中英

Getting all subsets within a data frame and listing all factors in R

I am faced with a problem in R that involves subsets. I have to make a list of all the unique factors within a subset in R but I have been doing it via for loop .

For example, I have a data frame below:

       area         family    
 [1,] "Location 1" "Diaz"    
 [2,] "Location 1" "Santiago"
 [3,] "Location 2" "Peralta" 
 [4,] "Location 2" "Perez"   
 [5,] "Location 2" "Cooper"  
 [6,] "Location 3" "Tesla"   
 [7,] "Location 3" "Tatum"   
 [8,] "Location 4" "Brown"   
 [9,] "Location 4" "Lee"     
 [10,] "Location 4" "Anthony" 

What I need for an output is below:

[[1]]
[1] "Diaz" "Santiago"

[[2]]
[1] "Peralta" "Perez" "Cooper"

[[3]]
[1] "Tesla" "Tatum"

[[4]]
[1] "Brown" "Lee" "Anthony"

Can anyone help me in simplifying this process?

Thank you.

我们可以使用split将'family'列除以vector list中的'area'列

split(df[,'family'], df[, 'area'])

此外,可以考虑by

by(df, df[, "area"], function(x) x[,"family"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM