user2543622
user2543622

Reputation: 6766

writing a data.frame using cat

How can I add/append data.frame abc to the text file that I have opened previously. I am writing some important information to that file and then I want to append that data.frame below that information. I get an error when I try to write the data.frame abc using cat.

fileConn<-file("metadata.txt","w+")
smoke <- matrix(c(51,43,22,92,28,21,68,22,9),ncol=3,byrow=TRUE)
smoke <- as.data.frame(smoke)
table <- sapply (smoke, class)
abc <- data.frame(nm = names(smoke), cl = sapply(unname(smoke), class))
cat("some imp info","\n", file=fileConn)
cat(abc,"\n", file=fileConn)
close(fileConn)
class(abc)

Upvotes: 8

Views: 7362

Answers (3)

Matifou
Matifou

Reputation: 8880

To make sure the output is readable, you could use also knitr::kable(). This will print your table as character, which has the advantage that you can embed it directly within the cat() call. It has lso several printing options (digits, align, row.names) etc that make it easy to control for how your table is printed:

tab <- knitr::kable(head(swiss))

cat("This is my file:",
    "Some important note about it",
    tab,
    sep="\n")
#> This is my file:
#> Some important note about it
#> |             | Fertility| Agriculture| Examination| Education| Catholic| Infant.Mortality|
#> |:------------|---------:|-----------:|-----------:|---------:|--------:|----------------:|
#> |Courtelary   |      80.2|        17.0|          15|        12|     9.96|             22.2|
#> |Delemont     |      83.1|        45.1|           6|         9|    84.84|             22.2|
#> |Franches-Mnt |      92.5|        39.7|           5|         5|    93.40|             20.2|
#> |Moutier      |      85.8|        36.5|          12|         7|    33.77|             20.3|
#> |Neuveville   |      76.9|        43.5|          17|        15|     5.16|             20.6|
#> |Porrentruy   |      76.1|        35.3|           9|         7|    90.57|             26.6|

Upvotes: 2

lukeA
lukeA

Reputation: 54237

Try this

capture.output(abc, file = fileConn)

Upvotes: 2

eddi
eddi

Reputation: 49448

Just use the standard tools for writing data.frame's, i.e. write.table:

write.table(abc, 'yourfile', append=TRUE) # plus whatever additional params

Upvotes: 4

Related Questions