将字符串拆分为行和列 [英] Split string into rows and columns
本文介绍了将字符串拆分为行和列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个很长很长的字符串:
I have one long enormous string:
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 但我似乎无法弄清楚如何创建新行.任何帮助表示赞赏!
By using the +
to create new rows, then spaces to create columns. Is this possible? I tried using str_split and mutate but I couldn't seem to figure out how to create new rows. Any help appreciated!
推荐答案
将+
替换为\n
read.table> 在 base R
We can use read.table
after replacing the +
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
和 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
这篇关于将字符串拆分为行和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文