R 将字符串拆分为行和列

R 将字符串拆分为行和列,r,string,mutate,R,String,Mutate,我有一根长长的绳子: mystr <- "foo one undefined + foo two undefined + BAR three undefined + " 使用+创建新行,然后使用空格创建列。这可能吗?我尝试使用str_split和mutate,但我似乎不知道如何创建新行。感谢您的帮助 在base R中使用gsub将+替换为\n后,我们可以使用read.table read.table(text = gsub("+", "\n", mystr, fi

我有一根长长的绳子:

mystr <- "foo   one   undefined + foo   two   undefined + BAR   three   undefined + "

使用
+
创建新行,然后使用空格创建列。这可能吗?我尝试使用str_split和mutate,但我似乎不知道如何创建新行。感谢您的帮助

base R
中使用
gsub
+
替换为
\n
后,我们可以使用
read.table

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
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
库(dplyr)
图书馆(tidyr)
TIBLE(col1=mystr)%>%
单独的\u行(col1,sep=“\\s*\\+\\s*”)%>%
分离(col1,分为=c('x1','x2','x3'))%>%
省略
#一个tibble:3x3
#x1x2x3
#        
#1个foo一个未定义
#2 foo 2未定义
#3条3未定义

另一个基本R解决方案:

data.frame(do.call("rbind", sapply(strsplit(trimws(mystr, "both"), "\\+"), 
        function(x){strsplit(trimws(x, "both"), "\\s+")})))
data.frame(do.call("rbind", sapply(strsplit(trimws(mystr, "both"), "\\+"), 
        function(x){strsplit(trimws(x, "both"), "\\s+")})))