有同学问到这个,简单的记录一下
一、合并矩阵
#这里取iris数据作演示
data <- iris
data
#分别取5行作为矩阵a和矩阵b
a <- iris[1:5,]
b <- iris[51:55,]
#合并矩阵,cbind是合并列,rbind是合并行
dat1 <- rbind(a,b)
dat2 <- cbind(a,b)
二、给矩阵分组
1.stringr包
二分组的话最方便就是用ifelse函数str_detect函数,用dat1演示
x <- ifelse(str_detect(dat$Species,"setosa"),"group1","group2")
dat1$group <- x
2.tidyverse包
用tidyverse包的mutate函数,我用iris取了三类Species做矩阵dat2
library(tidyverse)
length(which(dat2$Species=="setosa")) #每个分组的样本个数
a1 <- mutate(dat1[str_detect(dat2$Species,"setosa"),],group=rep("group1",5))#5是刚刚获取setosa分组的样本个数
b1 <- mutate(dat1[str_detect(dat2$Species,"versicolor"),],group=rep("group2",5))
c1 <- mutate(dat1[str_detect(dat2$Species,"virginica"),],group=rep("group3",5))
x <- rbind(a1,b1,c1)#合并矩阵
这两个小方法适用于大部分情况了,虽然简单,但是实用。