Home > OS >  How to make a output result as a table form in R
How to make a output result as a table form in R

Time:07-21

I am having the three output results as below,

structure(c("[1] \"lls_loess\" \"lls_rlr\"   \"knn_loess\"", 
"[1] \"lls_loess\" \"lls_rlr\"   \"knn_loess\"", "[1] \"lls_loess\" \"lls_rlr\"   \"lls_vsn\"  "
), dim = c(1L, 3L), dimnames = list(NULL, c("Based_on_PCV", "Based_on_PEV", 
"Based_on_PMAD")))

I have used the names() code for extracting the names from the result output.

And I want to give the output to the user in the format as in the picture. example result format

Please suggest some R code for this matter.

CodePudding user response:

Well... this is some quite ugly data, one possible solution

x=structure(c("[1] \"lls_loess\" \"lls_rlr\"   \"knn_loess\"", 
            "[1] \"lls_loess\" \"lls_rlr\"   \"knn_loess\"", "[1] \"lls_loess\" \"lls_rlr\"   \"lls_vsn\"  "
), dim = c(1L, 3L), dimnames = list(NULL, c("Based_on_PCV", "Based_on_PEV", 
                                            "Based_on_PMAD")))
df=data.frame(x)

data.frame(
  sapply(
    sapply(
      df,
      function(i){
        strsplit(
          gsub('"',",",gsub('\\[[0-9] \\]| ',"",i)),
          ","
        )
      }
    ),
    function(j){j[j!=""]}
  )
)

  Based_on_PCV Based_on_PEV Based_on_PMAD
1    lls_loess    lls_loess     lls_loess
2      lls_rlr      lls_rlr       lls_rlr
3    knn_loess    knn_loess       lls_vsn

CodePudding user response:

A tidyverse solution:

library(tidyverse)

x %>%
  as_tibble() %>%
  separate_rows(everything(), sep = "\"\\s \"") %>%
  mutate(across(, str_remove_all, "\\s|\"|\\[.\\]"))

# # A tibble: 3 × 3
#   Based_on_PCV Based_on_PEV Based_on_PMAD
#   <chr>        <chr>        <chr>
# 1 lls_loess    lls_loess    lls_loess
# 2 lls_rlr      lls_rlr      lls_rlr      
# 3 knn_loess    knn_loess    lls_vsn
  • Related