Writing list contents to one file in R
I have a list of data summaries and I would like to write them all into one file, so I can have one text file containing the call output summary()
for each data frame.
I've tried this:
dflist = lapply(1:4, function(x){df = data.frame(SID=paste("S",1:10,sep=""),matrix(runif(100),nrow=10,ncol=10))})
sumlist = lapply(dflist, function(df){summary(df)})
lapply(sumlist, function(i){write(i,"all_data_summary.txt",append=T )})
and that's kind of a job, but it writes the summary levels of each variable to a new line and doesn't include the variable name like:
S1 :1
S10 :1
S2 :1
S3 :1
S4 :1
S5 :1
(Other):4
Min. :0.1557
1st Qu.:0.2284
Median :0.5109
Mean :0.4707
3rd Qu.:0.6471
Max. :0.9509
NA
Min. :0.05512
1st Qu.:0.14310
Median :0.20889
Mean :0.41891
3rd Qu.:0.78261
Max. :0.97565
NA
Min. :0.01937
1st Qu.:0.23876
Median :0.57103
Mean :0.50806
3rd Qu.:0.70491
Max. :0.95610
NA
Min. :0.0212
1st Qu.:0.3445
Median :0.5634
Mean :0.5554
3rd Qu.:0.7484
Max. :0.9797
I would like the result to be like this:
List Element 1
SID X1 X2 X3 X4
S1 :1 Min. :0.1557 Min. :0.05512 Min. :0.01937 Min. :0.0212
S10 :1 1st Qu.:0.2284 1st Qu.:0.14310 1st Qu.:0.23876 1st Qu.:0.3445
S2 :1 Median :0.5109 Median :0.20889 Median :0.57103 Median :0.5634
S3 :1 Mean :0.4707 Mean :0.41891 Mean :0.50806 Mean :0.5554
S4 :1 3rd Qu.:0.6471 3rd Qu.:0.78261 3rd Qu.:0.70491 3rd Qu.:0.7484
S5 :1 Max. :0.9509 Max. :0.97565 Max. :0.95610 Max. :0.9797
(Other):4
List Element 2
SID X1 X2 X3 X4
S1 :1 Min. :0.1557 Min. :0.05512 Min. :0.01937 Min. :0.0212
S10 :1 1st Qu.:0.2284 1st Qu.:0.14310 1st Qu.:0.23876 1st Qu.:0.3445
S2 :1 Median :0.5109 Median :0.20889 Median :0.57103 Median :0.5634
S3 :1 Mean :0.4707 Mean :0.41891 Mean :0.50806 Mean :0.5554
S4 :1 3rd Qu.:0.6471 3rd Qu.:0.78261 3rd Qu.:0.70491 3rd Qu.:0.7484
S5 :1 Max. :0.9509 Max. :0.97565 Max. :0.95610 Max. :0.9797
Any ideas? Hurray, Davy.
source to share
Your suggested output looks like standard printed output, so you can just take the approach of capturing the printed output to a file. One easy way is to use the feature sink
and then lapply
print your resume. Or you can use capture.output
and save the results yourself (if you want to change or test something before saving).
If it doesn't, then take a look at the code for the print function that generates the output, and see if you can change that to put the information in a file. It looks like the pivot function on the dataframe is returning a symbol table, so print.table
would be a place to start.
source to share
Have you considered converting the output to yaml and saving it to a text file?
- It is human readable which is basically what you want (I suppose).
- You can restore the original data structure from a text file.
I think the package is called yaml.
Of course, if you wanted the output in the exact format you provided, I couldn't agree more with the accepted answer.
source to share