我们可以用read.table
更换后+
with \n
using gsub
in base R
read.table(text = gsub("+", "\n", mystr, fixed = TRUE),
header = FALSE, col.names = paste0('x', 1:3))
# x1 x2 x3
#1 foo one undefined
#2 foo two undefined
#3 BAR three undefined
或者使用strsplit
with read.table
read.table(text = strsplit(mystr, " + ", fixed = TRUE)[[1]], header = FALSE)
或者我们可以使用fread
library(data.table)
fread(text = gsub("+", "\n", mystr, fixed = TRUE), header = FALSE)
或者使用tidyverse
library(dplyr)
library(tidyr)
tibble(col1 = mystr) %>%
separate_rows(col1, sep="\\s*\\+\\s*") %>%
separate(col1, into = c('x1', 'x2', 'x3')) %>%
na.omit
# A tibble: 3 x 3
# x1 x2 x3
# <chr> <chr> <chr>
#1 foo one undefined
#2 foo two undefined
#3 BAR three undefined