【问题标题】:function to calculate how many observations in a data frame beyond a particular value in R [closed]用于计算数据框中有多少观察值超出 R 中特定值的函数 [关闭]
【发布时间】:2015-03-25 05:32:54
【问题描述】:

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

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

提前致谢:)

【问题讨论】:

  • 请尝试自己进行一些研究。在 Google 上快速搜索提供了一些很好的示例:onetwothree。此外,对于您实际尝试过的代码问题,这是一个很棒的论坛,所以请告诉我们您到目前为止做了什么,以及哪些地方没有起作用。最后,请阅读this

标签: r summarization


【解决方案1】:

使用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

【讨论】:

  • 根据您的解决方案,library(data.table); setDT(my.df)[, list(lapply(.SD, function(x) which(abs(x) &gt; 2.5))), ] 将提供一个接近 OP 请求的 data.table。
  • 很好,如果您不介意,我会将其添加到我的答案中。
  • 拜托,做。这与您的答案几乎相同。
  • @ Dominic Thnks。它工作.. :)
  • 很高兴。不客气!
【解决方案2】:

你也可以这样做:

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)]))

【讨论】:

猜你喜欢
  • 2016-06-26
  • 1970-01-01
  • 1970-01-01
  • 2022-12-06
  • 1970-01-01
  • 2020-03-18
  • 2021-12-11
  • 2022-12-08
  • 2020-03-16
相关资源
最近更新 更多