Dav*_*RGP 6 r switch-statement
switch() 接受它作为第一个参数
"EXPR表达式,用于评估数字或字符串."
但是,是否可以强制使用逻辑?如果是这样,我在这段代码中做了别的错吗?
我有一个包含数据框中逻辑值的列,我想根据逻辑参数编写一个包含数据框中现有数据值的新列:
exampleCurrent <- data.frame(value = c(5.5, 4.5, 4, 2.9, 2),
off = as.logical(c("F", "F", "T", "T", "F")),
extremeValue = as.logical(c("F", "F", "F", "F", "T")),
eclMinWork = c(5, 5.3, 5, 4.7, 3),
eclMinOff = c(4, 3.2, 3, 4, 3))
Run Code Online (Sandbox Code Playgroud)
我想谈谈这个问题:
exampleWanted <- data.frame(value = c(5.5, 4.5, 4, 2.9, 2),
off = as.logical(c("F", "F", "T", "T", "F")),
extremeValue = as.logical(c("F", "F", "F", "F", "T")),
eclMinWork = c(5, 5.3, 5, 4.7, 4),
eclMinOff = c(4, 3.2, 3, 4, 3),
output = c(5, 4.5, 3, 2.9, 3))
Run Code Online (Sandbox Code Playgroud)
选择号码的规则是:
off.如果off为FALSE,请从value或中选择eclMinWork.如果off为TRUE,请从value或中选择eclMinOffextremeValue.如果extreneValue= FALSE,请选择value步骤1中较小的和字段.如果extremeValue= TRUE,请从步骤1中的字段中选择值.我已经成功地写了一个ifelse()表演,但我想知道我是否可以使用switch.
exampleGenerated <- cbind(exampleCurrent, bestCase =
switch(exampleCurrent$off,
FALSE = ifelse(exampleCurrent$value<exampleCurrent$eclMinWork,exampleCurrent$value, exampleCurrent$eclMinWork),
TRUE = ifelse(exampleCurrent$value<exampleCurrent$eclMinOff,exampleCurrent$value, exampleCurrent$eclMinOff)))
Run Code Online (Sandbox Code Playgroud)
上面抛出一个错误,我假设FALSE不是一个字符,并且(在它的表面上)不是数字或字符:
Error: unexpected '=' in: switch(exampleCurrent$off, FALSE ="
Run Code Online (Sandbox Code Playgroud)
但是,我在包装as.numeric和as.character变量周围的尝试也失败了.有没有办法做到这一点,或者我错过了我的代码中的根本错误?
您不需要switch执行此任务.使用ifelse和更容易pmin:
tmp <- with(exampleCurrent, ifelse(off, eclMinOff, eclMinWork))
transform(exampleCurrent,
bestCase = ifelse(extremeValue, tmp, pmin(value, tmp)))
# value off extremeValue eclMinWork eclMinOff bestCase
# 1 5.5 FALSE FALSE 5.0 4.0 5.0
# 2 4.5 FALSE FALSE 5.3 3.2 4.5
# 3 4.0 TRUE FALSE 5.0 3.0 3.0
# 4 2.9 TRUE FALSE 4.7 4.0 2.9
# 5 2.0 FALSE TRUE 3.0 3.0 3.0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2668 次 |
| 最近记录: |