欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

R语言基础Lecture6

程序员文章站 2022-07-12 17:08:42
...

因子(Factor)

> factor = factor(rep(c(1:3),time=5))#1到3循环5次
> factor
 [1] 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
Levels: 1 2 3
> X=sample(100,15)#从1~100中抽取15个
> tapply(X,factor,mean)#求level等于1、2、3的平均值
   1    2    3 
67.6 52.2 56.8 
> rbind(X,factor)
       [,1] [,2] [,3] [,4] [,5] [,6] [,7]
X        97   87   93   34   16   67   48
factor    1    2    3    1    2    3    1
       [,8] [,9] [,10] [,11] [,12] [,13]
X        43   25    77    21    60    82
factor    2    3     1     2     3     1
       [,14] [,15]
X         94    39
factor     2     3
#验证
> rbind(X,factor)[2,]==1#取出X中factor为1的数
 [1]  TRUE FALSE FALSE  TRUE FALSE FALSE
 [7]  TRUE FALSE FALSE  TRUE FALSE FALSE
[13]  TRUE FALSE FALSE
> boo = rbind(X,factor)[2,]==1#作为判断条件
> which(boo)#返回True的数的下标
[1]  1  4  7 10 13
> rbind(X,factor)[1,which(boo)]#取出下标对应的值
[1] 97 34 48 77 82
> sum(rbind(X,factor)[1,which(boo)])/length(which(boo))#求平均值
[1] 67.6
相关标签: R语言