r - 将字符串拆分为行和列

标签 r string dplyr

我有一根又长又大的绳子:

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

或者将strsplitread.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/

相关文章:

Javascript计算字符串的频率字母

r - 使用 dplyr 计算时间戳上的累积和

r - 跨多个列检测关键字并在新列中分别标记它们

r - bwplot 的 boxplot lwd 参数等效

r - 奇怪的阿布林行为

r - 如何将组合成单行的数据分开?

postgresql - 使用 R 在 PostgreSQL 中建立非线性回归模型

c - 如何使用相同的函数对 C 中的字符串进行 XOR 加扰并再次加扰?

python - 如何将 python timedelta 转换为具有前导零的字符串,以便它保留格式 "00:00:00"(%HH :%MM:%SS)

r - 在 R 中按组创建连续年份的计数