【问题标题】:Split string into rows and columns将字符串拆分为行和列
【发布时间】:2020-07-30 11:39:15
【问题描述】:

我有一根长长的大绳子:

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 但我似乎无法弄清楚如何创建新行。任何帮助表示赞赏!

【问题讨论】:

    标签: r string dplyr


    【解决方案1】:

    另一种 Base R 解决方案:

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

    【讨论】:

      【解决方案2】:

      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
      

      或者使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-16
        • 1970-01-01
        相关资源
        最近更新 更多