R语言如何将字符串列拆分转换为指定格式的data.frame
解决方法
你遇到的问题是字段内部包含空格,无法直接按空格拆分。可以用正则分组提取的方式精准匹配每个字段,推荐使用tidyr::extract实现,代码如下:
library(tidyr) library(dplyr) df2 <- df1 %>% extract( col = value, into = paste0("v", 1:5), regex = "^(\\d+)\\s+([A-Z](?:\\s[A-Z])?)\\s+((?:G\\s)?P)\\s+(\\d+|Absent)\\s+(\\d+|Absent)$", convert = TRUE )
运行后得到的df2和你期望的输出完全一致,convert = TRUE参数会自动将可转换为数值的列转为数值类型,不需要额外手动处理。
如果不想加载tidyverse系列包,也可以用base R实现:
pattern <- "^(\\d+)\\s+([A-Z](?:\\s[A-Z])?)\\s+((?:G\\s)?P)\\s+(\\d+|Absent)\\s+(\\d+|Absent)$" matches <- regmatches(df1$value, regexec(pattern, df1$value)) df2 <- setNames( data.frame(do.call(rbind, matches), stringsAsFactors = FALSE)[,-1], paste0("v", 1:5) ) # 手动转换列类型 df2$v1 <- as.integer(df2$v1) df2$v4 <- ifelse(df2$v4 == "Absent", df2$v4, as.numeric(df2$v4)) df2$v5 <- ifelse(df2$v5 == "Absent", df2$v5, as.numeric(df2$v5))
内容的提问来源于stack exchange,提问作者MYaseen208
相关产品推荐
相关产品推荐

