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

R语言拆分不同长度位置字符串并保持字段位置匹配的实现

R 拆分不定长位置列解决方案

最优方案(tidyr 1.2.0及以上版本)

直接使用tidyr新版提供的separate_wider_delim函数,设置too_few = "align_end"参数即可实现拆分元素不足时从右侧列开始对齐填充,完全符合你的需求:

library(tidyverse)

# 测试数据
tib <- tribble(~obs, ~location,
1, "Miami, Florida, United States",
2, "Astrakhan Oblast, Russia",
3, "Mozambique")

# 核心代码
tib %>% 
  separate_wider_delim(
    col = location,
    delim = ", ",
    names = c("city", "state", "country"),
    too_few = "align_end"
  )

运行后直接得到目标结果:

# A tibble: 3 × 4
    obs city  state            country      
  <dbl> <chr> <chr>            <chr>        
1     1 Miami Florida          United States
2     2 NA    Astrakhan Oblast Russia
3     3 NA    NA               Mozambique

兼容旧版tidyr的方案

如果使用的tidyr版本低于1.2.0没有separate_wider_delim函数,可以用字符串拆分+列表补位的方式实现,代码同样简洁易读:

tib %>% 
  mutate(parts = str_split(location, ", ")) %>% 
  # 对拆分后的向量左侧补NA到固定长度3
  mutate(parts = map(parts, ~ c(rep(NA, 3 - length(.x)), .x))) %>% 
  # 列表展开为列
  unnest_wider(parts, names_repair = ~ c("obs", "location", "city", "state", "country")) %>% 
  select(-location)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:15:00