You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按分隔符拆分含不同分隔符数量的单列至多列

解决方案

可以用tidyverse工具包中的str_split()结合unnest_wider()实现自动适配分隔符数量的拆分,无需预先指定列数,步骤如下:

  1. 加载tidyverse包(包含dplyr和tidyr等工具)
  2. 将country列按分号拆分为列表格式的新列
  3. 把列表列展开为多列,自动为短记录补充NA
  4. 重命名生成的新列为country1、country2...格式

完整代码示例:

library(tidyverse)

# 原始数据
continent <- c("Europe", "Asia")
country <- c("France;Germany;Italy", "Japan")
start_problem <- data.frame(continent, country)

# 处理数据
result <- start_problem %>%
  mutate(country_list = str_split(country, ";")) %>%
  unnest_wider(country_list, names_sep = "") %>%
  rename_with(~paste0("country", seq_along(.x)), starts_with("country_list")) %>%
  select(-country)

# 查看结果
result

如果预先知道最大列数(比如这里最多3个国家),也可以用separate_wider_delim()并设置too_many="align"参数解决:

start_problem %>%
  separate_wider_delim(
    country, 
    delim = ";", 
    names = paste0("country", 1:3), 
    too_many = "align"
  )

两种方法都能得到你需要的目标数据格式。

内容的提问来源于stack exchange,提问作者Noah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 12:47:08