我想对R中的每一行应用一个函数,该行“得分”一行x的每个值 . 好像我在R中使用'apply'函数来做这件事,但不知道该怎么做 . 我想输入一个带有整数值列的数据帧,并使用得分的矢量输出 . 我现在的代码如下:
ScoreFn <- function(x){
score <- 0
if(x<1) {
score <- 0
} else if(x==1) {
score <- 5
} else if(x==2) {
score <- 10
} else if(x==3) {
score <- 20
} else if(x >= 4 && x <= 10) {
score <- 30
} else if(x >= 11 && x <= 20) {
score <- 40
} else if(x >= 21) {
score <- 50
}
return(score)
}
apply(df$x, 1, ScoreFn())
此外,我收到此消息 . 不确定执行此功能的最佳方法 .
1: In if (x < 1) { :
the condition has length > 1 and only the first element will be used
2: In if (x == 1) { :
the condition has length > 1 and only the first element will be used
3: In if (x == 2) { :
the condition has length > 1 and only the first element will be used
4: In if (x == 3) { :
the condition has length > 1 and only the first element will be used
...
2 回答
您可以使用剪切创建矢量化函数,因此您根本不必使用apply:
这也有一个好处,即减少输入if / elses的重量,以及比非矢量化版本快10倍 .
它的工作原理是将给定的矢量(在这种情况下为
df$x
)切割成由切片给出的因子 . 然后我们用你的分数标记它们,然后使用as.character
和as.numeric
再次输出数字 .如果您的输入只是data.frame的一列,则不需要使用
apply
. 您可以改用sapply
.