split - R - Subset of matrix based on cell value of one column -
split - R - Subset of matrix based on cell value of one column -
hi there
i have matrix (is.matrix(users)=true) x users , 7 columns. first column indicates male/female either 0 or 1. how can split matrix 2 new matrices. 1 boys scores , 1 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 seek split
lst <- setnames(lapply(split(1:nrow(mat1), mat1[,"sex"]), function(i) mat1[i,]), c("girls", "boys"))
if need 2 datasets instead of keeping in list (i prefer have in 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))
r split subset
Comments
Post a Comment