我在尝试通过在条件语句中使用管道运算符根据第二个 df 中可用的国家/地区过滤第一个 df 中的数据时出错。
引用国家 df
Overall_top5
########### output ###########
continent country gdpPercap
Africa Botswana 8090
Africa Equatorial Guinea 20500
Africa Gabon 19600
Africa Libya 12100
Africa Mauritius 10900
Americas Canada 51600
Americas Chile 15100
Americas Trinidad and Tobago 17100
Run Code Online (Sandbox Code Playgroud)
主文件
gap_longer
########### output #############
country year gdpPercap continent
Australia 2019 57100 Oceania
Botswana 2019 8090 Africa
Canada 2019 51600 Americas
Chile 2019 15100 Americas
Denmark 2019 65100 Europe
Run Code Online (Sandbox Code Playgroud)
错误:当我尝试下面的代码时,它给了我错误:
gap_longer %>%
filter(year == 2019,
country %in% Overall_top5 %>% select(country) )
Error: Problem with `filter()` input `..1`. x no applicable method for 'select_' applied to an object of class "logical" i Input `..1` is `country %in% Overall_top5 %>% select(country)`. Run `rlang::last_error()` to see where the error occurred.
Run Code Online (Sandbox Code Playgroud)
如何使用管道运行它?我可以使用 base R 运行它,但不知道如何使用 pipe 修复它。
gap_longer %>%
filter(year == 2019,
country %in% Overall_top5$country )
Run Code Online (Sandbox Code Playgroud)
原始数据
Overall_top5
########### output ###########
continent country gdpPercap
Africa Botswana 8090
Africa Equatorial Guinea 20500
Africa Gabon 19600
Africa Libya 12100
Africa Mauritius 10900
Americas Canada 51600
Americas Chile 15100
Americas Trinidad and Tobago 17100
Run Code Online (Sandbox Code Playgroud)
首先,您想要使用pull而不是selectasselect将返回数据帧而不是向量(但这并不能解决您的问题)。
您的问题来自优先级。在您的示例中,%in%首先评估,然后评估%>%。要解决此问题,请使用括号。
gap_longer %>%
filter(
year == 2019,
country %in% (Overall_top5 %>% pull(country))
)
#> # A tibble: 3 x 4
#> country year gdpPercap continent
#> <chr> <dbl> <dbl> <chr>
#> 1 Botswana 2019 8090 Africa
#> 2 Canada 2019 51600 Americas
#> 3 Chile 2019 15100 Americas
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
54 次 |
| 最近记录: |