美文网首页
初识R语言—分组数据处理

初识R语言—分组数据处理

作者: 超级无敌大蜗牛 | 来源:发表于2020-04-02 22:49 被阅读0次
#用list函数将list里面的向量和income一一对应进行计算
#创建数据集df1
> age <- c(18,19,23,14,15)
> sex <- c('F','M','F','F','M')
> income <- c(2000,3000,5500,4300,1900)
> education <- c("高中","初中","高中","博士","初中")
> df1 <- data.frame(age,sex,income,education)
> df1
  age sex income education
1  18   F   2000      高中
2  19   M   3000      初中
3  23   F   5500      高中
4  14   F   4300      博士
5  15   M   1900      初中
 #需求1:想知道男女各自收入总和
#需求2:想知道不同性别不同学历的人群的平均收入
  • tapply(vector, INDEX, FUN)
    vector:要计算的变量
    INDEX:分组变量
    FUN:函数
> tapply(df1$income,df1$sex,sum)
    F     M 
11800  4900 
> tapply(df1$income,list(df1$sex,df1$education),mean)
  初中 博士 高中
F   NA 4300 3750
M 2450   NA   NA
  • by(data, INDEX,FUN)
    data:要计算的变量
    INDEX: 分组变量
    FUN: 函数
#by函数
> by(df1$income,df1$sex,sum)
df1$sex: F
[1] 11800
-------------------------------------------------------- 
df1$sex: M
[1] 4900
> by(df1$income,list(df1$sex,df1$education),mean)
: F
: 初中
[1] NA
-------------------------------------------------------- 
: M
: 初中
[1] 2450
-------------------------------------------------------- 
: F
: 博士
[1] 4300
-------------------------------------------------------- 
: M
: 博士
[1] NA
-------------------------------------------------------- 
: F
: 高中
[1] 3750
-------------------------------------------------------- 
: M
: 高中
[1] NA
  • aggregate(x~x1+x2+..., data, FUN)
    x要计算的变量
    x1,x2...:分组变量x1,x2...
    data:数据集
    FUN:函数
> #aggregate函数
> aggregate(income~sex,df1,sum)
  sex income
1   F  11800
2   M   4900
> aggregate(income~sex+education,df1,sum)
  sex education income
1   M      初中   4900
2   F      博士   4300
3   F      高中   7500

总结:推荐aggregate

相关文章

网友评论

      本文标题:初识R语言—分组数据处理

      本文链接:https://www.haomeiwen.com/subject/qdcqphtx.html