如何通过分隔符将一列拆分为多列(分隔符的个数不同)

问题描述 投票:0回答:1

我有一个这样的数据框:

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()
不起作用,因为并非每个大陆都有相同数量的国家,因此原始列中的分隔符数量不同。

提前致谢

r dataframe delimiter
1个回答
0
投票

我们可以先通过找到分隔符

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>
© www.soinside.com 2019 - 2024. All rights reserved.