我正在处理一些数据集,并且我创建了一个管理数据的功能:
library(dplyr)
testResults <- data.frame(
X1 = c(431,432,433,434, 756),
counter = c(4,5,6,7,5),
Type = rep("ud", 5),
Granularity = rep("package", 5),
SeverityScore = c(5,6,2,4,10)
)
level.fun <- function(Type, Granularity, SeverityScore){
ifelse(as.character(Type) == "ud" && as.character(Granularity) == "package",
ifelse(SeverityScore <= 8,1,
ifelse(SeverityScore <= 19,2,
ifelse(SeverityScore <= 41,3,
ifelse(SeverityScore <= 116,4,
ifelse(SeverityScore <= 608,5,0))))),0)
testResults <- mutate(testResults, SeverityScoreLevel = level.fun(Type, Granularity, SeverityScore))
它只是检查一些值并根据ifelse中的条件返回结果。 问题是我所有的回报都是1:
即使在控制台中,如果我尝试level.fun(testResults$Type[756], testResults$Granularity[756], testResults$SeverityScore[756])
,结果为2,这是正确的。第761行也是如此。
我甚至认为使用for来滑动所有行,但是使用更聪明的功能。
答案 0 :(得分:1)
欢迎来到SO!
改变&amp;&amp; (返回整个矢量的单个T / F)到&amp;:
library(dplyr)
testResults <- data.frame(
X1 = c(431,432,433,434, 756),
counter = c(4,5,6,7,5),
Type = rep("ud", 5),
Granularity = rep("package", 5),
SeverityScore = c(5,6,2,4,10)
)
level.fun <- function(Type, Granularity, SeverityScore){
ifelse(as.character(Type) == "ud" & as.character(Granularity) == "package",
ifelse(SeverityScore <= 8,1,
ifelse(SeverityScore <= 19,2,
ifelse(SeverityScore <= 41,3,
ifelse(SeverityScore <= 116,4,
ifelse(SeverityScore <= 608,5,0))))),0)
}
mutate(testResults, SeverityScoreLevel = level.fun(Type, Granularity, SeverityScore))
## X1 counter Type Granularity SeverityScore SeverityScoreLevel
## 1 431 4 ud package 5 1
## 2 432 5 ud package 6 1
## 3 433 6 ud package 2 1
## 4 434 7 ud package 4 1
## 5 756 5 ud package 10 2
HTH James