[英]Count number of rows in a dataframe having different number of rows for each column
[英]Count number of rows in each column in a dataframe that specify a specific condition
R 的新手顺便说一句,如果这看起来像一个愚蠢的问题,我很抱歉。 所以基本上我有一个 dataframe 有 100 行和 3 个不同的数据列。 我还有一个带有 3 个阈值的向量,每列一个。 我想知道如何过滤掉每列中优于每个阈值的值。
编辑:对不起不完整的问题。 So essentially what i would like to create is a function (that takes a dataframe and a vector of tresholds as parameters) that applies every treshold to their respective column of the dataframe (so there is one treshhold for every column of the dataframe). 每列中“尊重”其阈值的元素数量稍后应放入向量中。 例如:
第 1 列:值 = 1、2、3。 阈值 =(仅限低于 3 的值)第 2 列:值 = 4、5、6。 阈值 =(仅低于 6 的值) Output:向量 (2,2),因为每列中有两个元素位于各自的阈值之下。
谢谢大家的帮助!!
您的示例数据:
df <- data.frame(a = 1:3, b = 4:6)
threshold <- c(3, 6)
解决您的问题的一种选择是使用sapply()
,它将 function 应用于列表或向量。 在这种情况下,我使用1:ncol(df)
为df
中的列创建一个向量。 在 function 内部,您可以通过求和 TRUE 案例的数量来计算小于给定阈值的值的数量:
col_num <- 1:ncol(df)
sapply(col_num, function(x) {sum(df[, x] < threshold[x])})
或者,在一行中:
sapply(1:ncol(df), function(x) {sum(df[, x] < threshold[x])})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.