在没有示例数据集的情况下,此解决方案基于推测以及您如何描述您想要完成的操作。
library("dplyr")
library("stringr")
library("purrr")
clean.data <- tribble(
~bilateral, ~if.bilateral.other.party,
"Y", "UK,Netherlands",
"Bilateral", "Sweden,France",
"N", "Germany,UK"
)
clean.data
#> # A tibble: 3 x 2
#> bilateral if.bilateral.other.party
#> <chr> <chr>
#> 1 Y UK,Netherlands
#> 2 Bilateral Sweden,France
#> 3 N Germany,UK
# Split and count countries and assign new bilateral column
clean.data %>%
mutate(list_countries = str_split(if.bilateral.other.party, ",")) %>%
mutate(num_countries = map_int(list_countries, function(x) { length(x) })) %>%
mutate(new_bilateral = case_when(
num_countries > 1 & bilateral %in% c("Y", "Bilateral") ~ "N",
num_countries > 1 & bilateral == "N" ~ "Y",
TRUE ~ bilateral
))
#> # A tibble: 3 x 5
#> bilateral if.bilateral.other.party list_countries num_countries new_bilateral
#> <chr> <chr> <list> <int> <chr>
#> 1 Y UK,Netherlands <chr [2]> 2 N
#> 2 Bilateral Sweden,France <chr [2]> 2 N
#> 3 N Germany,UK <chr [2]> 2 Y
由reprex package (v0.3.0) 于 2020 年 12 月 12 日创建
以下是使用您提供的样本数据得出的结果。
clean.data <- data.frame(
"bilateral" = c("Y", "Bilateral", "N", "Y", "Y", "N"),
"if.bilateral.other.party" = c("Jordan", "Sweeden", NA, "Uk,Netherlands", "Russia,Poland", "NewZealand"),
stringsAsFactors = FALSE)
clean.data %>%
mutate(list_countries = str_split(if.bilateral.other.party, ",")) %>%
mutate(num_countries = map_int(list_countries, function(x) { length(x) })) %>%
mutate(new_bilateral = case_when(
num_countries > 1 & bilateral %in% c("Y", "Bilateral") ~ "N",
num_countries > 1 & bilateral == "N" ~ "Y",
TRUE ~ bilateral
))
#> bilateral if.bilateral.other.party list_countries num_countries
#> 1 Y Jordan Jordan 1
#> 2 Bilateral Sweeden Sweeden 1
#> 3 N <NA> NA 1
#> 4 Y Uk,Netherlands Uk, Netherlands 2
#> 5 Y Russia,Poland Russia, Poland 2
#> 6 N NewZealand NewZealand 1
#> new_bilateral
#> 1 Y
#> 2 Bilateral
#> 3 N
#> 4 N
#> 5 N
#> 6 N
由reprex package (v0.3.0) 于 2020-12-12 创建