Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write list to a text file, preserving names, R

Tags:

list

r

I want to write a list to a text file, preserving the names.

This is similar to R: Print list to a text file but with names which I want to print out also, at the start of each line:

> print(head(mylist,2))
$first
[1] 234984  10354  41175 932711 426928
$second
[1] 1693237   13462

mylist.txt
first   234984  10354  41175 932711 426928
second  1693237   13462

Any ideas?

Many thanks.

like image 445
Jim Bo Avatar asked Nov 24 '11 19:11

Jim Bo


2 Answers

@42-

To add to 42-'s answer (should have been a comment but then i couldn't format the code)

I needed to print also the names of the element's of the vectors in the list, so I added this line above the cat statement, as follows:

mylist <- list(first =c( a = 234984,  b = 10354,  c = 41175, d = 932711, e = 426928), 
           second =c( A = 1693237, B = 13462))


fnlist <- function(x, fil){ z <- deparse(substitute(x))
cat(z, "\n", file=fil)
nams=names(x) 
for (i in seq_along(x) ){ 
  cat("", "\t", paste(names(x[[i]]), "\t"), "\n", file=fil, append=TRUE)
  cat(nams[i], "\t",  x[[i]], "\n", file=fil, append=TRUE) }
}
fnlist(mylist, "test")

result

mylist 
         a      b     c      d     e     
first    234984 10354 41175 932711 426928 
         A       B   
second   1693237 13462 
like image 170
Marco Stamazza Avatar answered Oct 19 '22 22:10

Marco Stamazza


The cat function will print to a device (console by default) and not add any of the usual annotations, but it cannot accept a list as an argument, so everything needs to be an atomic vector. The deparse( substitute()) gambit is the way to recover names of lists that were passed to a function. Just using names(x) inside the function fails to recover the name of the original argument.

 mylist <- list(first =c( 234984,  10354,  41175, 932711, 426928), 
                second =c(1693237, 13462))
 fnlist <- function(x){ z <- deparse(substitute(x))
                         cat(z, "\n")
                         nams=names(x) 
                   for (i in seq_along(x) ) cat(nams[i],  x[[i]], "\n")}
 fnlist(mylist)
mylist 
second 234984 10354 41175 932711 426928 
first 1693237 13462 

This version would output a file (and you could substitute "\t" if you wanted tabs between names and values

fnlist <- function(x, fil){ z <- deparse(substitute(x))
                         cat(z, "\n", file=fil)
                         nams=names(x) 
                   for (i in seq_along(x) ){ cat(nams[i], "\t",  x[[i]], "\n", 
                                            file=fil, append=TRUE) }
                         }
 fnlist(mylist, "test")
like image 24
IRTFM Avatar answered Oct 19 '22 23:10

IRTFM