我有一个数字框,数字列在R中.我想看看数据框每列中有多少值超过某个阈值.(例如标准值大于+ -2.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
Run Code Online (Sandbox Code Playgroud)
要获得与您在问题中提供的格式接近的格式,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
Run Code Online (Sandbox Code Playgroud)
为了获得总数,对于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
Run Code Online (Sandbox Code Playgroud)