我有一根又长又大的绳子:
mystr <- "foo one undefined + foo two undefined + BAR three undefined + "
我想把它变成
x1 x2 x3
1 foo one undefined
2 foo two undefined
3 bar three undefined
通过使用 +
创建新行,然后使用空格创建列。这可能吗?我尝试使用 str_split 和 mutate 但我似乎无法弄清楚如何创建新行。任何帮助表示赞赏!
最佳答案
我们可以在 中使用
gsub
将 +
替换为 \n
后使用 read.table
基础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
与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
关于r - 将字符串拆分为行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61263676/