【发布时间】: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