我们遍历'df1'的列 (
lapply(df1, ..
),使用
sub
在数字子字符串后创建分隔符,使用
read.table
将
vector
读取为data.frame,
rbind
data.frames
列表,并更改输出的列名称。
res <- do.call(cbind, lapply(df1, function(x)
read.table(text=sub("(\\d+)", "\\1,", x),
header=FALSE, sep=",", stringsAsFactors=FALSE)))
colnames(res) <- scan(text=names(df1), sep=".", what="", quiet = TRUE)
res
或者使用
tidyr
中的
separate
函数。
library(tidyr)
library(dplyr)
separate(df1, age.gen, into = c("age", "gen"), "(?<=\\d)(?=[A-Za-z])", convert= TRUE) %>%
separate(surv.camp, into = c("surv", "camp"), "(?<=\\d)(?=[A-Za-z])", convert = TRUE)
或者,正如@Frank提到的那样,我们可以使用data.table中的tstrsplit函数。
library(data.table)
setDT(df1)[, unlist(lapply(.SD, function(x)
tstrsplit(x, "(?<=[0-9])(?=[a-zA-Z])", perl=TRUE,
type.convert=TRUE)), recursive = FALSE)]
编辑:在separate
中添加了convert = TRUE
,以改变分割后列的type
。
数据
df1 <- structure(list(age.gen = c("45M", "9F", "12M", "67M"), surv.camp = c("1LC",
"0", "1AC", "1LC")), .Names = c("age.gen", "surv.camp"),
class = "data.frame", row.names = c(NA, -4L))
strsplit()
函数,并通过使用perl
保存分割值。你的代码是什么? - Rich Scriven