首页 > 解决方案 > 在“if”子句中使用复合语句

问题描述

我发现了一个涉及模板的类似问题,超出了我的问题范围。我希望能够说类似的话:if (a and b) then (do something)。这是一个例子:

t1 <- tribble(
    ~state,     ~county,
    "New York", "Bronx",
    "New York", "Richmond",
    "New York", "Albany",
    "Virginia", "Richmond"
    )

five_boroughs = c("Bronx", "Kings", "New York", "Queens", "Richmond")

if t1$state == "New York" && t1$county in five_boroughs
    t1$county = "New York City"

使用 &、&&、in 或 %in% 将纽约市置于弗吉尼亚州。我为打电话给县区的纽约人道歉。

标签: rif-statementcol

解决方案


我们可以用case_when

library(dplyr)
library(stringr)
t1 %>% 
   mutate(county = case_when(state == 'New York' & 
          county %in% five_boroughs~ str_c(state, ' City')))

推荐阅读