【问题标题】:Remove a row based on a value in a column using if statements使用 if 语句根据列中的值删除行
【发布时间】:2021-07-10 09:04:49
【问题描述】:

我希望创建一个函数,如果 B 列中的值小于整列的平均值,它将删除一行。

testing<-function(x){
for(n in x){
    if(n < mean(n){
    *drop the entire row*
    }

到目前为止,我只能让 R 删除值本身,而不是整行,因此使用此函数的示例方法是

df$columnB <- testing(df$columnB)

因此,函数本身的输入仅来自其中一列,但在函数内部,它需要知道删除整行而不仅仅是该列,因此仅 drop(n) 是不够的。

使用以下方法进行测试:

iris_tibble<-as_tibble(iris)

#all values became NA and message saying "argument is not numeric or logical: returning NA"
testing <- function(x) {
  i <- x[,"Sepal.Length"] < mean(x[,"Sepal.Length"])
  return( x[!i,] )
}
testing(iris_tibble)

#Goal
testing <- function(x,y){
  i <- x[,y] < mean(x[,y])
  return( x[!i,] )
}

testing(iris_tibble,"Sepal.Length")

【问题讨论】:

    标签: r function for-loop if-statement


    【解决方案1】:

    这就够了:

    
    testing <- function(x, colname) {
        i <- x[,colname] < mean(x[,colname,drop=TRUE])
        return( x[!i,] )
    }
    
    dim( iris )
    dim( testing( as_tibble(iris), "Sepal.Length" ) )
    
    ## cust roughly half of iris away
    
    

    你应该给它你的整个data.frame和一个列名,例如。 testing(df, "foobar"),并捕获它返回的内容。

    【讨论】:

    • 谢谢!根据您的回答,我试图使 B 列变得灵活,我将其设置为 function(x,y) 然后将代码中的所有“columnB”替换为 y,因为有时该列具有不同的名称和位置。但是它生成了一个错误代码,说“'list' object cannot be coerced to type 'double'”,但是当我 glimpse() nothing is a list时,难道不能让代码那样工作吗?
    • 此时您必须在问题中包含全部或部分数据
    • 目前还没有数据集,但我现在复制了虹膜数据以进行测试并更新了问题以将其包含在底部
    • 查看我更新的答案,以在 iris 上运行为例.. 对于你需要 drop=TRUE 的小标题,请查看更新的答案
    • 非常感谢!如果我想预先计算平均值,以便分配 i 的行可以更清晰,特别是如果我在公式中添加更多(例如平均值 x 2),以下是否正确? testing &lt;- function(x, colname) { mean_col = mean(x[,colname,drop=TRUE]) i &lt;- x[,colname] &lt; mean_col*2 return(x[!i,]) }
    猜你喜欢
    • 2019-02-20
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-18
    相关资源
    最近更新 更多