convert a list of tab delimited strings into dataframe

Viewed 32

I have a list of strings with tabs like below:

xx <- list("raw total sequences:\t67166250", "1st fragments:\t33583125")
yy <- list("raw total sequences:\t190999", "1st fragments:\t222")

I want to have "row total sequences" and "1st fragments" as column names and the numeric values as column values and xx and yy as row names. How can I do it efficiently?

1 Answers

You may create one named list combining the individual lists that you have so that it is easier to work with them. return_df_from_list function captures the data in two capture groups, one before the colon (as column name) and second after the colon as value and returns a dataframe.

We apply the function to each list and combine them in one dataframe using map_df.

library(dplyr)

list_data <- lst(xx, yy)

return_df_from_list <- function(x) {
  value <- stringr::str_match(x, '(.*):\t(.*)')
  setNames(data.frame(t(value[, 3])), value[, 2])  
}

result <- purrr::map_df(list_data, return_df_from_list, .id = "rowname") %>%
  column_to_rownames() %>% 
  type.convert(as.is = TRUE) 

result

#   raw total sequences 1st fragments
#xx            67166250      33583125
#yy              190999           222
Related