【发布时间】:2021-06-29 10:41:23
【问题描述】:
我尝试在 R 中编写一个函数,该函数将数据帧中的多个变量作为输入,并给出一个带有结果的向量作为输出。
根据下面的这篇文章,我确实编写了下面的函数。 How can create a function using variables in a dataframe
虽然我收到了这条警告信息:
the condition has length > 1 and only the first element will be used
我试图通过下面的帖子在函数中使用 sapply 来解决它,尽管我没有成功。 https://datascience.stackexchange.com/questions/33351/what-is-the-problem-with-the-condition-has-length-1-and-only-the-first-elemen
# a data frame with columns a, x, y and z:
myData <- data.frame(a=1:5,
x=(2:6),
y=(11:15),
z=3:7)
myFun3 <- function(df, col1 = "x", col2 = "y", col3 = "z"){
result <- 0
if(df[,col1] == 2){result <- result + 10
}
if(df[,col2] == 11){result <- result + 100
}
return(result)
}
myFun3(myData)
> Warning messages:
> 1: In if (df[, col1] == 2) { :
> the condition has length > 1 and only the first element will be used
> 2: In if (df[, col2] == 11) { :
> the condition has length > 1 and only the first element will be used
谁能解释我如何将函数应用于数据框的所有行? 非常感谢!
【问题讨论】:
标签: r function dataframe sapply