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

R语言如何将拆分后的字符串转为text和num两列?附示例

问题:将字符串拆分结果转为数据框的"text"和"num"列

我已经用以下R代码完成了字符串拆分:

df <- c("Abc1038")

df <- strsplit(df, "(?=[A-Za-z])(?<=[0-9])|(?=[0-9])(?<=[A-Za-z])", perl=TRUE)

# 拆分结果
# [[1]]
# [1] "Abc"  "1038"

现在想把拆分结果转为数据框的两列,分别命名为"text"和"num",该怎么实现?


单值场景解决方法

可以通过do.call(rbind, ...)将拆分后的列表转为矩阵,再转为数据框并重命名列:

# 执行拆分
split_result <- strsplit(c("Abc1038"), "(?=[A-Za-z])(?<=[0-9])|(?=[0-9])(?<=[A-Za-z])", perl=TRUE)

# 转为指定列名的数据框
result_df <- do.call(rbind, split_result) |>
  data.frame() |>
  rename(text = X1, num = X2)

print(result_df)
#   text  num
# 1  Abc 1038

批量数据完整处理示例

针对多数据行的场景,完整处理流程如下:

# 构造初始数据框
column_one <- c("1234 AB 12/30/24 A23 One","4567 CD 05/30/24 B29 TWO")
column_two <- c("1","2")
df <- data.frame(col_one = column_one, col_two = column_two)

print(df)
#                   col_one col_two
# 1 1234 AB 12/30/24 A23 One       1
# 2 4567 CD 05/30/24 B29 TWO       2

# 拆分col_one列并按到期日排序
df <- separate(df, col_one, c("Number","Text","Expiration","Product","Type"), sep=" ")
df <- df[order(df$Expiration),] 

# 拆分Product列并转为带指定列名的结构
df$N1 <- strsplit(df$Product, "(?=[A-Za-z])(?<=[0-9])|(?=[0-9])(?<=[A-Za-z])", perl=TRUE)
df$N1 <- do.call(rbind, df$N1)|>
  data.frame()|>
  rename(text = X1, num = X2)

print(df)
#  Number Text Expiration Product Type col_two N1.text N1.num
# 2   4567   CD   05/30/24     B29  TWO       2       B     29
# 1   1234   AB   12/30/24     A23  One       1       A     23

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 07:44:53