Ste*_*ady 5 statistics r dataframe
刚刚学习R.
如果data.frame
R中有两列,一个是数字,一个是分类,我如何提取一部分data.frame
用于?
str(ex0331)
'data.frame': 36 obs. of 2 variables:
$ Iron : num 0.71 1.66 2.01 2.16 2.42 ...
$ Supplement: Factor w/ 2 levels "Fe3","Fe4": 1 1 1 1 1 1 1 1 1 1 ...
Run Code Online (Sandbox Code Playgroud)
基本上,我需要能够分别对这两个因素进行操作; 即我需要能够按Supplement
类型(Fe3
或Fe4
)单独确定铁保留率的长度/平均值/标准差/秒等.
最简单的方法是什么?
我知道这个by()
命令.例如,以下内容得到了我需要的一些内容:
by(ex0331, ex0331$Supplement, summary)
ex0331$Supplement: Fe3
Iron Supplement
Min. :0.710 Fe3:18
1st Qu.:2.420 Fe4: 0
Median :3.475
Mean :3.699
3rd Qu.:4.472
Max. :8.240
------------------------------------------------------------
ex0331$Supplement: Fe4
Iron Supplement
Min. : 2.200 Fe3: 0
1st Qu.: 3.892 Fe4:18
Median : 5.750
Mean : 5.937
3rd Qu.: 6.970
Max. :12.450
Run Code Online (Sandbox Code Playgroud)
但我需要更多的灵活性.我需要应用axis
命令,例如,log()
按组应用功能.我确信有一个简单的方法可以做到这一点; 我只是没有看到它.data.frame
我见过的所有操作文档都是数字而不是分类变量.
您可以通过索引或使用来获取数据的子集subset
:
ex0331 <- data.frame( iron=rnorm(36), supplement=c("Fe3","Fe4"))
subset(ex0331, supplement=="Fe3")
subset(ex0331, supplement=="Fe4")
ex0331[ex0331$supplement=="Fe3",]
Run Code Online (Sandbox Code Playgroud)
或者立即使用split
,产生一个列表:
split(ex0331,ex0331$supplement)
Run Code Online (Sandbox Code Playgroud)
您可以做的另一件事是使用tapply
一个因子进行分割,然后执行一个函数:
tapply(ex0331$iron,ex0331$supplement,mean)
Fe3 Fe4
-0.15443861 -0.01308835
Run Code Online (Sandbox Code Playgroud)
也可以使用该plyr
包,它有很多有用的功能。例如:
library(plyr)
daply(ex0331,.(supplement),function(x)mean(x[1]))
Fe3 Fe4
-0.15443861 -0.01308835
Run Code Online (Sandbox Code Playgroud)
为了回答已编辑的问题,您可以通过以下方式获取每种补充剂的铁含量:
ex0331 <- data.frame( iron=abs(rnorm(36)), supplement=c("Fe3","Fe4"))
tapply(ex0331$iron,ex0331$supplement,log)
Run Code Online (Sandbox Code Playgroud)
或者与plyr
:
library(plyr)
dlply(ex0331,.(supplement),function(x)log(x$iron))
Run Code Online (Sandbox Code Playgroud)
两者都以列表形式返回。我确信有一种比 plyr 示例中的包装函数更简单的方法。
归档时间: |
|
查看次数: |
23515 次 |
最近记录: |