Reputation: 734
I want to write a data frame to a file using the write
function, however this doesnt work, because data.frame()
creates it as a list.
Reproductive example:
data <- data.frame(cbind(1:2,3:4))
typeof(data)
data
# X1 X2
#1 1 3
#2 2 4
#> typeof(data)
#[1] "list"
Now when I want to write to file using
write(data,"data.txt")
I get an error saying
Error in cat(list(...), file, sep, fill, labels, append) : argument 1 (type 'list') cannot be handled by 'cat'
Which obviously happens because data is a list, but I dont understand why it is a list. Im running R 3.1.3
Upvotes: 3
Views: 2454
Reputation: 39
A data.frame is a list of vector structures of the same length. You can use typeof (df)
to see that it shows the type of df (here an example data.frame) as "list".
You can use write.table to write a data.frame to a text file as shown below:
write.table(df, "filename.txt", sep = "\t", row.names = FALSE)
Upvotes: 1
Reputation: 20329
Actually, your data
is a data.frame
:
class(data)
# [1] "data.frame"
The problem is that write
does not cope well with data frames, but would work with matrices:
write(as.matrix(data), "test.txt")
If you want to write the data frame to a file use write.table
:
write.table(data, "test.txt")
The error message comes from the underlying cat
function and the fact that a data.frame
is conceptually a list of vectors of same length.
Upvotes: 6