通过将某些子字符串放在一起分割字符串

问题描述 投票:0回答:1

我想通过某些分隔字符(例如,空格,逗号和分号)分割数据框中的字符列。但是,我想从拆分中排除某些短语(在我的示例中,我想排除“我的测试”)。

我设法将普通的字符串分割开了,但是不知道如何排除某些短语。

library(tidyverse)

test <- data.frame(string = c("this is a,test;but I want to exclude my test",
                              "this is another;of my tests",
                              "this is my 3rd test"),
                   stringsAsFactors = FALSE)

test %>%
  mutate(new_string = str_split(test$string, pattern = " |,|;")) %>%
  unnest_wider(new_string)

这给:

# A tibble: 3 x 12
  string                                       ...1  ...2  ...3    ...4  ...5  ...6  ...7  ...8  ...9    ...10 ...11
  <chr>                                        <chr> <chr> <chr>   <chr> <chr> <chr> <chr> <chr> <chr>   <chr> <chr>
1 this is a,test;but I want to exclude my test this  is    a       test  but   I     want  to    exclude my    test 
2 this is another;of my tests                  this  is    another of    my    tests NA    NA    NA      NA    NA   
3 this is my 3rd test                          this  is    my      3rd   test  NA    NA    NA    NA      NA    NA

但是,我想要的输出是(不包括“我的测试”):

# A tibble: 3 x 12
  string                                       ...1  ...2  ...3    ...4  ...5      ...6  ...7  ...8  ...9    ...10
  <chr>                                        <chr> <chr> <chr>   <chr> <chr>     <chr> <chr> <chr> <chr>   <chr>
1 this is a,test;but I want to exclude my test this  is    a       test  but       I     want  to    exclude my test 
2 this is another;of my tests                  this  is    another of    my tests  NA    NA    NA    NA      NA   
3 this is my 3rd test                          this  is    my      3rd   test      NA    NA    NA    NA      NA

有什么想法吗? (旁边的问题:知道如何在unnest_wider中命名列吗?)

r dplyr tidyr strsplit
1个回答
0
投票

一个简单的解决方法是添加一个_并在以后将其删除:

test %>%
  mutate(string = gsub("my test", "my_test", string),
    new_string = str_split(string, pattern = "[ ,;]")) %>%
  unnest_wider(new_string) %>%
  mutate_all(~ gsub("my_test", "my test", .x))

为了给列赋予更有意义的名称,您可以使用pivot_wider中的其他选项。

© www.soinside.com 2019 - 2024. All rights reserved.