如何简化基R中嵌套ifelse()结构的处理? [英] How to simplify handling with nested ifelse() structures in base R?
问题描述
我正面临嵌套的 ifelse()
结构:
df1$var <- ifelse(x < a, u, ifelse(x < b, v, ifelse(x < c, w, ...)))
其中 u,v,w,...
s实际上是函数。
一个愚蠢的工作示例将是
A dumbed down working example would be
df1 <- data.frame(x = rbinom(100, 5, .5))
df1$y <- ifelse(x == 1, "s", ifelse(x == 2, "t",
ifelse(x == 3, "u", ifelse(x == 4, "v", "w"))))
我认为理想情况下可能存在 基础R 方法(为了速度而 )简化此类代码;最终函数为
I presume there could be ideally a base R method (for sake of speed) to simplify such code; eventually a function as
rave.ifelse(x, 1=s, 2=t, ...)
我瞥了一眼 cut(x,5)
但是从这个角度来看,这让我很困惑。
I took a glance at cut(x, 5)
but it confused me from this point of view.
注意: x
的值可以无论是数字还是因素, ==
也可以是任何逻辑运算符, s,t,...
是实际上功能。
Note: Values of x
could be either numbers or factors, ==
could also be any logical operator and the s, t, ...
are actually functions.
编辑:
edit:
注意: ifelse()
的数量已知并且很大。解决方案确实应该适合 df1 $ var< - ifelse(x< a,u,ifelse(x< b,v,ifelse(x< c,w,...)) ))
情况,当 u,v,w,...
s是函数时,例如 u = sample(0:9,1),v = runif(1),...
。它不应该明显慢于 ifelse()
。
Note: The number of ifelse()
s is known and large. The solution really should fit to the df1$var <- ifelse(x < a, u, ifelse(x < b, v, ifelse(x < c, w, ...)))
situation, when the u, v, w, ...
s are functions, e.g. u=sample(0:9, 1), v=runif(1),...
. It should not be significantly slower than ifelse()
.
推荐答案
In base R
,如果要替换多个元素,请创建一个键/值数据集并执行 merge
In base R
, if there are multiple elements to be replaced, create a key/value dataset and do a merge
keyval <- data.frame(x = c(1, 2, 3, 4), y = c("s", "t", "u", "v"), stringsAsFactors = FALSE)
new <- merge(df1, keyval, by = 'x', all.x = TRUE)[['y']]
new[is.na(new)] <- "w"
df1$x <- new
数据
data
set.seed(24)
df1 <- data.frame(x = rbinom(100, 5, .5))
这篇关于如何简化基R中嵌套ifelse()结构的处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!