I have the following kind of DataFrame output written in R. I would like to convert DataFrame containing only the lists (here named as 'score') to a CSV file.
So, my output in the CSV file should be the lists in each row:
7, 2, 12, ...
80, 23, 144, ...
93, 22, 167, ...
46, 40, 49, ...
48, 1, 5, ...
I have tried these codes:
export.wig(tiled_chr, paste0(outDir, species1, "_", species2, "_", chrom, "_", window_size/1000, "kb_min_window.wig"))
write.csv(tiled_chr, paste0(outDir, 'my_file.csv'), row.names=F)
dput(tiled_chr, file = paste0(outDir, 'new_file.csv'))
The output of dput:
CodePudding user response:
If you want a text file (not CSV), try this:
dt <- tibble(x=c(1,2,3), y=list(list(1,2,4), list(5,6,7), list(8,9,9,10,11,12)))
dt_text <- unlist(lapply(dt$y, paste, collapse=","))
fileConn<-file("output.txt")
writeLines(dt_text, fileConn)
close(fileConn)
If you want a CSV table:
dt <- tibble(x=c(1,2,3), y=list(list(1,2,4), list(5,6,7), list(8,9,9,10,11,12)))
n <- max(sapply(dt$y, length))
a <-sapply(dt$y, function(x, n) c(x, rep(NA, n-length(x))), n)
a <-t(as_tibble(a))
write.table(a, "output.csv", sep=",", row.names = F, col.names = F)
CodePudding user response:
Based on lumartor data, you can also use purrr::map_chr and readr::write_lines to create csv lines
delim <- "," # ";"
library(dplyr)
dt <- tibble(x=c(1,2,3), y=list(list(1,2,4), list(5,6,7), list(8,9,9,10,11,12)))
lines_ <- dt$y %>%
purrr::map_chr(function(x)paste0(x, collapse = delim))
readr::write_lines(lines_, 'output_1.csv')


