简体   繁体   中英

R - Subset of matrix based on cell value of one column

Hi there

I have this matrix (is.matrix(users)=TRUE) with X users and 7 columns. The first column indicates male/female with either a 0 or a 1. How can I split this matrix into two new matrices. One with all the boys scores and one with all the girls scores.

I Have

USERS

All users

         sex     intelligence   ...    status  
user1      0             1234   ...       ...
user2      1             5678   ...       ...
user3      1             8765   ...       ...
...      ...              ...   ...       ...
userX      0             4321   ...       ...

I need

BOYS

         sex     intelligence   ...    status  
user2      1             5678   ...       ...
user3      1             8765   ...       ...

GIRLS

         sex     Intelligence   ...    status  
user1      0             1234   ...       ...
userX      0             4321   ...       ...

you can convert matrix to dataframe and subset it

df <- as.data.frame(users)
girls <- df[df$sex == 0, ]
boys <- df[df$sex == 1, ]

If you need matrix again:

girls <- as.matrix(girls)
boys <- as.matrix(boys)

You could try split

lst <- setNames(lapply(split(1:nrow(mat1), mat1[,"sex"]), function(i) mat1[i,]), c("GIRLS", "BOYS"))

If you need two datasets instead of keeping it in a list (I would prefer to have it in a list)

 list2env(lst, envir=.GlobalEnv)
 <environment: R_GlobalEnv>
 GIRLS
 #      sex intelligence
 #[1,]   0         1236
 #[2,]   0         1241


 BOYS

data

 set.seed(42)
 mat1 <- as.matrix(data.frame(sex=sample(0:1, 10, replace=TRUE), intelligence=1234:1243))

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