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

在R语言中以括号为分隔符拆分列为两列的方法求助

解决方案

方法一:使用tidyverse工具包(推荐,代码简洁易读)

先构造数据框,再通过separate拆分列,最后清理col2的多余符号:

library(tidyverse)

# 原始数据
col <- c("142343-2344343(+)", "546354-4775458(-)", "374637463")
df <- tibble(col = col)

# 拆分并整理
result <- df %>%
  separate(col, into = c("col1", "col2"), sep = "\\(", extra = "merge", fill = "right") %>%
  mutate(col2 = str_remove(col2, "\\)"))

print(result)

运行后输出:

# A tibble: 3 × 2
  col1             col2 
  <chr>            <chr>
1 142343-2344343   +    
2 546354-4775458   -    
3 374637463        NA   

方法二:基础R实现(无需额外安装包)

通过正则表达式直接提取目标内容:

# 原始数据
col <- c("142343-2344343(+)", "546354-4775458(-)", "374637463")

# 提取col1:第一个括号前的内容
col1 <- sub("\\(.*", "", col)

# 提取col2:括号内的符号,无括号则设为NA
col2 <- sub(".*\\((.)\\).*", "\\1", col)
col2[col2 == col] <- NA

# 组合成结果数据框
result <- data.frame(col1, col2, stringsAsFactors = FALSE)

print(result)

运行后输出:

col1 col2
1 142343-2344343    +
2 546354-4775458    -
3      374637463 <NA>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:40:03