Grep文本并放入数据框

Grep文本并放入数据框,r,dataframe,R,Dataframe,由于使用了forecast软件包中的checkresiduals()函数,我得到了以下结果: #Result of checkresiduals() function test <- "Q* = 4.5113, df = 4.6, p-value = 0.4237" 有人能帮我写这段代码吗?你可以使用strsplit tmp <- do.call(cbind, strsplit(strsplit(test, ", ")[[1]], " = ")) d <- setNames(

由于使用了
forecast
软件包中的
checkresiduals()
函数,我得到了以下结果:

#Result of checkresiduals() function
test <- "Q* = 4.5113, df = 4.6, p-value = 0.4237"

有人能帮我写这段代码吗?

你可以使用
strsplit

tmp <- do.call(cbind, strsplit(strsplit(test, ", ")[[1]], " = "))
d <- setNames(data.frame(t(as.numeric(tmp[2, ]))), tmp[1, ])
#       Q*  df p-value
# 1 4.5113 4.6  0.4237

tmp这里有一种使用
tidyverse的方法

library(tidyverse)
tibble(test) %>% 
    separate_rows(test, sep = ",\\s*") %>% 
    separate(test, into = c("v1", 'v2'), sep= " = ") %>% 
    deframe %>%
    as.list %>% 
    as_tibble
# A tibble: 1 x 3
#  `Q*`   df    `p-value`
#  <chr>  <chr> <chr>    
#1 4.5113 4.6   0.4237   

以下是两种备选方法:

  • 将字符串转换为DCF格式并使用
    read.DCF()
  • “在语言上计算”:将字符串转换为有效的R表达式,并使用
    parse()
    /
    eval()
  • read.dcf()
    将字符串
    test
    转换为dcf(Debian控制文件)格式后,使用
    read.dcf()
    函数。
    (顺便说一句,每个R包的
    说明
    文件是DCF格式。)

    所有列都是字符类型

    基于语言的计算 所有列均为双精度类型

    test %>%   
      stringr::str_replace_all("(\\S+) =", "`\\1` =") %>%   
      paste0("data.frame(", ., ", check.names = FALSE)")
    
    返回

    "data.frame(`Q*` = 4.5113, `df` = 4.6, `p-value` = 0.4237, check.names = FALSE)"
    
    然后将其解析为表达式并进行计算

    请注意,所有变量名都被引用以处理语法无效的变量名,如
    Q*
    p-value

    library(magrittr) # piping used for readability
    test %>% 
      stringr::str_replace_all("=", ":") %>%        # replace "=" by ":"
      stringr::str_replace_all(",\\s*", "\n") %>%   # replace ", " by line break
      textConnection() %>% 
      read.dcf(all = TRUE)
    
         Q*  df  p-value 
    1 4.5113 4.6   0.4237
    
    library(magrittr) # piping used for readability
    test %>%   
      stringr::str_replace_all("(\\S+) =", "`\\1` =") %>% 
      paste0("data.frame(", ., ", check.names = FALSE)") %>% 
      parse(text = .) %>% 
      eval()
    
          Q*  df p-value
    1 4.5113 4.6  0.4237
    
    test %>%   
      stringr::str_replace_all("(\\S+) =", "`\\1` =") %>%   
      paste0("data.frame(", ., ", check.names = FALSE)")
    
    "data.frame(`Q*` = 4.5113, `df` = 4.6, `p-value` = 0.4237, check.names = FALSE)"