嵌套 ifelse R 中的意外“(”
Unexpected "(" in nested ifelse R
我正在尝试 运行 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"))))
但我收到以下错误
Error: unexpected ')' in "ifelse(newdb$centile >=6 & newdb$centile < >9,"3","4"))"
我们不需要嵌套 ifelse
。通过指定 breaks
.
使用 cut
可以更容易地解决它
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
如果我们想在原始数据集中创建一个新列 ('group'),
newdb$group <- res
此外,OP代码中的多个newdb$
可以通过使用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))
我正在尝试 运行 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"))))
但我收到以下错误
Error: unexpected ')' in "ifelse(newdb$centile >=6 & newdb$centile < >9,"3","4"))"
我们不需要嵌套 ifelse
。通过指定 breaks
.
cut
可以更容易地解决它
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
如果我们想在原始数据集中创建一个新列 ('group'),
newdb$group <- res
此外,OP代码中的多个newdb$
可以通过使用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))