我正在尝试在R中运行以下代码行
new <- data.frame(newdb,
ifelse(newdb$centile >=0 & newdb$centile < 3,"1",
ifelse(newdb$centile >=3 & newdb$centile < 6,"2",
ifelse(newdb$centile >=6 & newdb$centile < 9,"3","4"))))
但是我收到以下错误
错误:“ ifelse(newdb $ centile> = 6&newdb $ centile <> 9,“ 3”,“ 4”))中出现意外的')'
我们不需要嵌套的ifelse
。cut
通过指定,可以更轻松地解决该问题breaks
。
res1 <- cut(newdb$centile, breaks=c(-Inf, 0, 3, 6, 9, Inf),
right=FALSE, labels=FALSE)-1
OP的代码与 ifelse
res <- ifelse(newdb$centile >=0 & newdb$centile < 3,"1",
ifelse(newdb$centile >=3 & newdb$centile < 6,"2",
ifelse(newdb$centile >=6 & newdb$centile < 9,"3","4")))
identical(as.numeric(res), res1)
#[1] TRUE
如果我们要在原始数据集中创建一个新列(“组”),
newdb$group <- res
同样,newdb$
可以通过使用OP避免代码中的倍数with
with(newdb,
ifelse(centile >=0 & centile < 3, '1',
ifelse(centile >=3 & centile < 6, '2',
ifelse(centile >=6 & centile < 9, '3', '4'))))
set.seed(24)
newdb <- data.frame(centile= sample(5:12, 25, replace=TRUE))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句