【问题标题】:dplyr mutate with str_locate_alldplyr 与 str_locate_all 发生变异
【发布时间】:2020-08-27 13:41:03
【问题描述】:

我想将字符串的开始和结束位置添加到 df 中。我知道如何使用 str_locate 来做到这一点,但是如何使用 str_locate_all 绑定所有预期的命中?

str_locate 示例:

library(dplyr)
library(stringr)

pattern <- "HelloHiHelloHi"

df <- data.frame(
  Text = c("Hello", "HelloHi", "Hi")
)

df <- df %>% rowwise() %>% mutate(Start = str_locate(pattern, Text)[[1]],
                    End = str_locate(pattern, Text)[[2]]) 

#result

  Text    Start   End
  <chr>   <int> <int>
1 Hello       1     5
2 HelloHi     1     7
3 Hi          6     7

我希望得到以下结果:

  Text        Start     End              
  <chr>       <int> <int>           
1 Hello           1     5 
2 Hello           8    12 
3 HelloHi         1     7 
4 HelloHi         8    14 
5 Hi              6     7 
6 Hi             13    14 

【问题讨论】:

  • 不确定你的意思。如果你这样做 df %&gt;% rowwise() %&gt;% mutate(Start = str_locate_all(pattern, Text), End = str_locate_all(pattern, Text)) 它会将所有点添加为嵌套列表
  • 如何取消嵌套这些列表,以便为每个位置获得一行?
  • 嗯,有unnest(),但你确定它们总是一样大吗?
  • 是的,我确信它们的大小始终相同。我试过: df % rowwise() %>% mutate(Start = str_locate_all(pattern, Text), End = str_locate_all(pattern, Text)) %>% unnest(Start) 但这不会导致如上所示的格式。
  • 不应该,因为这里有更多元素。可能我不是很了解。

标签: r dplyr stringr


【解决方案1】:

或带有base R 的选项(已使用的stringr 除外)

out <-  do.call(rbind, Map(data.frame, Text = df$Text, 
           str_locate_all(pattern, df$Text)))
row.names(out) <- NULL

【讨论】:

    【解决方案2】:
    df <- df %>% rowwise() %>% mutate(pos = list(
      data.frame(
       str_locate_all(pattern, Text)))) %>% unnest(pos) 
    
    #result
      Text    start   end
      <chr>   <int> <int>
    1 Hello       1     5
    2 Hello       8    12
    3 HelloHi     1     7
    4 HelloHi     8    14
    5 Hi          6     7
    6 Hi         13    14
    

    以上内容不再适用于新版本的 dplyr。我现在使用:

    df <- df %>%
        mutate(
          start = str_locate_all(pattern, text) %>%
              map(~ .x[,1]),
          end = str_locate_all(pattern, text) %>%
              map(~ .x[,2])) %>%
          unnest(cols=c(start, end))
    

    【讨论】:

      猜你喜欢
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 2019-12-06
      • 1970-01-01
      • 2016-05-08
      • 1970-01-01
      • 2017-09-27
      相关资源
      最近更新 更多