我有一个这样的数据框:
continent <- c("Europe", "Asia")
country <- c("France;Germany;Italy", "Japan")
start_problem <- data.frame(continent, country)
start_problem
我想将
country
列中的值分成多个列,每个国家一个。最终产品应该是这样的:
continent <- c("Europe", "Asia")
country1 <- c("France", "Japan")
country2 <- c("Germany", NA)
country3 <- c("Italy", NA)
goal <- data.frame(continent, country1, country2, country3)
goal
使用
separate_wider_delim()
不起作用,因为并非每个大陆都有相同数量的国家,因此原始列中的分隔符数量不同。
提前致谢
我们可以先通过找到分隔符
max
的;
出现次数来找出需要多少列。然后paste
在into =
的separate
参数中的信息与“国家”字符串。
library(tidyverse)
col_number <- max(str_count(start_problem$country, ";") + 1)
start_problem %>% separate(country,
into = paste0("country", seq_len(col_number)),
sep = ";")
continent country1 country2 country3
1 Europe France Germany Italy
2 Asia Japan <NA> <NA>