【问题标题】:R Separate column based on patternR基于模式分离列
【发布时间】:2019-11-02 10:27:30
【问题描述】:

我的数据集看起来像这样 -

dataset = data.frame(Comments=c('Wow... Loved this place.   1','Crust is not good.  0','Not tasty and the texture was just nasty.   0'))

我正在尝试将数据集拆分为两列,使第一列仅包含文本,第二列仅包含每个字符串末尾的数字。

这是我的尝试

library(dplyr)
library(tidyr)

dataset = dataset %>%
  separate(Comments, into = c("Comment", "Score"), sep = " (?=[^ ]+$)")

但是我没有得到完美的分离。我在网上查看了其他解决方案,但还没有运气。

对此的任何帮助将不胜感激。

【问题讨论】:

  • 你能在一个句点后面加上 >1 个空格吗?从您的示例数据集中,这将在这里工作

标签: r tidyr


【解决方案1】:

也许你可以使用substrgsub

dataset <- dataset %>%
  mutate(Comments = as.character(Comments)) %>%
  mutate(Score = substr(Comments, nchar(Comments), nchar(Comments))) %>%
  mutate(Comment = gsub("\\s\\d", "", Comments))

【讨论】:

    【解决方案2】:

    一种解决方案是利用stringr 函数:

    dataset %>% 
      mutate(Score = str_extract_all(Comments, pattern = "[:digit:]"), 
             Comments = str_remove_all(Comments, pattern = "[:digit:]") %>% str_trim())
    
    #                                   Comments Score
    #1                  Wow... Loved this place.     1
    #2                        Crust is not good.     0
    #3 Not tasty and the texture was just nasty.     0
    

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 2019-11-08
      • 2019-10-24
      • 1970-01-01
      • 2020-02-07
      相关资源
      最近更新 更多