用于计算超出R中特定值的数据帧中的观察数量

时间:2015-03-25 05:32:55

标签: r summarization

我在R中有一个数字列的数据框。我想看看数据帧每列中有多少值超过某个阈值。 (例如标准值大于+ -2.5) 这是我想要显示的输出

Output

假设我的数据框中的所有列都是数字的,我可以使用哪些函数或哪些函数组合来产生类似的结果?

提前感谢:)

2 个答案:

答案 0 :(得分:5)

使用lapply

可以轻松完成
# Generate sample data (10 columns x 100 rows) normally distributed around 0
my.df <- as.data.frame(matrix(rnorm(n=1000), ncol=10))

# Get the line numbers, for each column in the df
lapply(my.df, function(x) which(abs(x) > 2.5))

# $V1
# integer(0)
# 
# $V2
# [1] 29 69
# 
# $V3
# [1] 85
# 
# $V4
# [1] 100
# 
# $V5
# [1] 11 40
# 
# $V6
# [1] 89
# 
# $V7
# [1] 67
# 
# $V8
# [1] 49 68
# 
# $V9
# integer(0)
# 
# $V10
# [1]  7 27

要获得与您在问题中提供的格式相近的格式,ExperimenteR建议:

library(data.table)
setDT(my.df)[, list(lapply(.SD, function(x) which(abs(x) > 2.5))), ]


 #        V1
 #  1:      
 #  2: 29,69
 #  3:    85
 #  4:   100
 #  5: 11,40
 #  6:    89
 #  7:    67
 #  8: 49,68
 #  9:      
 # 10:  7,27

要获得总数,请为df中的每一列使用

lapply(my.df, function(x) sum(abs(x) > 2.5))

# $V1
# [1] 0
# 
# $V2
# [1] 2
# 
# $V3
# [1] 1
# 
# $V4
# [1] 1
# 
# $V5
# [1] 2
# 
# $V6
# [1] 1
# 
# $V7
# [1] 1
# 
# $V8
# [1] 2
# 
# $V9
# [1] 0
# 
# $V10
# [1] 2

答案 1 :(得分:0)

你也可以这样做:

library(reshape2); library(plyr)
#using data from @Dominic Comtois
my.df <- as.data.frame(matrix(rnorm(n=1000), ncol=10))

data = melt(my.df);
data2 = ddply(data,.(variable),summarise,length(value[(abs(value)>2.5)]))
相关问题