我要在另一个之后编写一个简单的ifelse语句,在这里我试图将索引分为三组(> = 0.8、0.8到-0.8,<= -0.8)
我不断收到错误消息:
如果if(df $ index> = 0.8){:条件的长度> 1并且仅 将使用第一个元素
d2 %>%
group_by(area) %>%
mutate(grp = election.dummy) %>%
fill(grp, .direction = "up") %>%
group_by(grp, add = TRUE) %>%
mutate(gdp = mean(gdp)) %>%
filter(!is.na(election.dummy)) %>%
ungroup %>%
select(-grp)
# A tibble: 4 x 4
# area year election.dummy gdp
# <int> <int> <dbl> <dbl>
#1 1 2002 1 3
#2 1 2006 2 2.5
#3 2 2002 1 4
#4 2 2006 2 4
答案 0 :(得分:4)
我们可以使用ifelse
代替if/else
,因为if/else
期望一个长度为1的向量,并且长度大于1时不被向量化。
df$indexclass <- with(df, ifelse(index >= 0.8, "P",
ifelse(index <= (-0.8), "A", "S")))
df$indexclass
#[1] "P" "S" "S" "S" "A" "A"
如果有多个比较,则选项为cut
或findInterval
c("A", "S","P")[with(df, findInterval(index, c(-0.8, 0.8))) + 1]
#[1] "P" "S" "S" "S" "A" "A"