如何访问列表中的元素而不会收到错误消息

我有通过str_extract函数创建的列表。该列表由字符串组成,我想将所有列表元素连接成一个字符串。不幸的是,当我尝试访问元素时,出现以下错误消息:

column must be of length (number of rows or one) not 2

我尝试了几种不同的处理方法,包括[[1]]和purrr :: pluck(),但始终遇到相同的错误。

这是带有示例代码的reprex:

library(tidyverse)

library(reprex)
library(kableExtra)


myStr <- 'Approaching the 1300 Metres, TAI PO FORTUNE blundered when being shifted in behind AMAZING GIFT. TAI PO FORTUNE then got its head up when racing keenly passing the 1000 Metres. Near the 800 Metres, COOL PAL was left racing wide and without cover. Passing the 300 Metres, SUPREME PROFIT lay in and proved reluctant to shift to the outside of DOUBLE DRAGON. SUPREME PROFIT continued to hang in under pressure and over the concluding stages raced tight outside GOLDWEAVER. Because of this, SUPREME PROFIT was not able to be properly tested over the concluding stages. DOUBLE DRAGON and PLAIN BLUE BANNER were sent for sampling.'
name <- "DOUBLE DRAGON"

df <- as_tibble(data.frame(name=c(name),text=c(myStr),stringsAsFactors = FALSE))

df <- df %>% 
  mutate(htext = str_extract_all(text,(str_c('(?<=^|\\.)[^.]*\\b',name,'\\b[^.]*\\.?')))) %>% 
  select(-text) %>% 
  mutate(type = typeof(htext)) %>% 
  kable() %>% 
  kable_styling()

Created on 2020-05-11 by the reprex package (v0.3.0)

评论
  • Oo熊猫
    Oo熊猫 回复

    You are replacing the data frame, df, with the output from the kable function (with styling). Stop before you pipe the data to kable:

    df2 <- df %>% 
      mutate(htext = str_extract_all(text,(str_c('(?<=^|\\.)[^.]*\\b',name,'\\b[^.]*\\.?')))) %>% 
      select(-text) %>% 
      mutate(type = typeof(htext)) 
    
    df2 %>% kable() %>% 
      kable_styling()
    

    Now you can access the elements of df2.

    df2$htext
    #[[1]]
    #[1] " Passing the 300 Metres, SUPREME PROFIT lay in and proved reluctant to shift to the outside of DOUBLE DRAGON."
    #[2] " DOUBLE DRAGON and PLAIN BLUE BANNER were sent for sampling."
    

    现在,您可以执行任何操作,包括将它们全部连接成一个字符串。

    paste(unlist(df2$htext), collapse=" : ") # or whatever you prefer.