【问题标题】:creating a new column based on a set of strings conditions [duplicate]根据一组字符串条件创建一个新列[重复]
【发布时间】:2021-01-05 18:59:23
【问题描述】:

我有很多国家的这个专栏。

countries <- c(Germany, France, Japan, China, Angola, Nigeria)

我想创建一个名为continent 的新列,聚合这些地方。例如,我试过这个,但它不起作用:

if (countries == "Germany" | "France" {
   countries$continents <- "Europe"
 } else if (countries == "Japan"  |"China") {
   countries$continents <- "Asia"
 } else if (countries == "Angola"  |"Nigeria") {
   countries$continents <- "África" 

但是 R 一直说我不允许比较字符串。 也许 dplyr 可能有一个聪明的解决方案,但欢迎任何解决方案。我该怎么做?

【问题讨论】:

  • 这篇文章可能会有所帮助:Get continent name from country name in R
  • 您需要使用的是%in%,例如countries %in% c("Germany", "France")。您将逻辑向量 (countries == "Germany") 与字符串 "France" 进行比较。

标签: r if-statement dplyr


【解决方案1】:

正如@markus 指出的那样,使用 %in%

你可以用dplyr试试这个


library(dplyr)

df <- data.frame(countries = c("Germany", "France", "Japan", "China", "Angola", "Nigeria"))



df1 <- 
  df %>% 
  mutate(continent = case_when(countries %in% c("Germany", "France") ~ "Europe",
                               countries %in% c("Japan", "China") ~ "Asia",
                               countries %in% c("Angola", "Nigeria") ~ "Africa"))

但正如@markus 所指出的,使用countrycode 包可能更简洁

library(countrycode)

df_continents <- 
  codelist %>% 
  select(country.name.en, continent)

df2 <- 
  df %>% 
  left_join(df_continents, by = c("countries" = "country.name.en"))

df2

#>   countries continent
#> 1   Germany    Europe
#> 2    France    Europe
#> 3     Japan      Asia
#> 4     China      Asia
#> 5    Angola    Africa
#> 6   Nigeria    Africa

reprex package (v0.3.0) 于 2020 年 9 月 18 日创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 2023-03-25
    • 2018-10-21
    • 1970-01-01
    • 2017-01-17
    • 2018-03-06
    相关资源
    最近更新 更多