把所有东西都放在 ?在带有 mutate 的 dplyr 链中的字符串中

Get everything to the left of ? in a string during dplyr chain with mutate

df <- data.frame(
  strings = c('blah?ha', 'foo?bar', 'cats?dogs')
)

df %>% 
  mutate(first_word = str_split(strings, fixed('?')))

     strings first_word
 strings first_word
1   blah?ha   blah, ha
2   foo?bar   foo, bar
3 cats?dogs cats, dogs

这让我接近我的目标。不过,我只想要第一部分,blah、foo 和猫。尝试过:

 df %>% 
+   mutate(first_word = str_split(strings, fixed('?'))[[1]][[1]])
    strings first_word
1   blah?ha       blah
2   foo?bar       blah
3 cats?dogs       blah

这让我在列中重复了同一个词。

如何获得包含值 blah、foo 和 cats 的新列?

我们可以使用str_extract来匹配一个或多个不是?[^?]+)从头开始(^)的字符串

library(dplyr)
library(stringr)
df %>%
   mutate(first_word = str_extract(strings, "^[^?]+"))

或者使用 trimwswhitespace 作为正则表达式

df %>%
    mutate(first_word = trimws(strings, whitespace = "\?.*"))

base R

中的类似代码
df$first_word <- with(df, trimws(strings, whitespace = "\?.*"))

OP 代码中的问题在于它仅从 str_split 中提取第一个 list 元素 ([[1]])。它需要遍历 list 并获得 first 元素

library(purrr)
df %>%
    mutate(first_word = map_chr(str_split(strings, fixed("?")), first))
#    strings first_word
#1   blah?ha       blah
#2   foo?bar        foo
#3 cats?dogs       cats