user27976
user27976

Reputation: 903

writing multiple lines of text into one file using R

I'm using write() to write multiple lines to the same file this way:

filename='out.txt'

write(c("\n\n","No of blues =", nrow(data1)), file=filename,append=FALSE)
write(c("\n\n","No of greens =", nrow(data2)), file=filename,append=Append)
write(c("\n\n","No of reds =", nrow(data3)), file=filename,append=Append)

data1, data2 and data3 are variable names.

But I got the following errors:

Error in cat(list(...), file, sep, fill, labels, append) : 
 argument 1 (type 'list') cannot be handled by 'cat'

Is there a solution in R for this problem?

Upvotes: 1

Views: 6765

Answers (2)

Jim
Jim

Reputation: 4767

just use cat directly instead of write

filename='out.txt'

data1 = matrix(1:10, ncol=2)
data2 = matrix(1:20, ncol=2)
data3 = matrix(1:30, ncol=2)

cat("No of blues =", nrow(data1), "\n", file=filename, append=FALSE, sep='')
cat("No of blues =", nrow(data2), "\n", file=filename, append=TRUE, sep='')
cat("No of blues =", nrow(data3), "\n", file=filename, append=TRUE, sep='')

#results
cat(readLines(filename), sep="\n")

## No of blues =5
## No of blues =10
## No of blues =15

You can also combine the three lines into one call to cat so there is no need to mess with appending to files, which is always a risky proposition.

cat("No of blues =", nrow(data1), "\n",
    "No of blues =", nrow(data2), "\n",
    "No of blues =", nrow(data3), "\n", file=filename, sep='')

#results
cat(readLines(filename), sep="\n")

## No of blues =5
## No of blues =10
## No of blues =15

Upvotes: 1

Spacedman
Spacedman

Reputation: 94317

At a guess, you are trying to write a data frame. This is a guess, because the lines you give us should work. I don't believe they are giving the error. An important part of asking questions on here is doing a bit of work yourself to find out where the error is, and supplying self-contained code that generates the error. Like this doesn't:

Append=TRUE
filename='out.txt'
data1=data.frame(x=1:10)
data2=data.frame(y=1:3)
data3=data.frame(z=99)
write(c("\n\n","No of blues =", nrow(data1)), file=filename,append=FALSE)
write(c("\n\n","No of greens =", nrow(data2)), file=filename,append=Append)
write(c("\n\n","No of reds =", nrow(data3)), file=filename,append=Append)

If I run that (and if YOU run that too) then I don't get an error. But try this:

write(c("\n\n","data 1 is ", data1), file=filename,append=Append)

and looky look:

Error in cat(list(...), file, sep, fill, labels, append) : 
  argument 1 (type 'list') cannot be handled by 'cat'

Exactly your error. Maybe that's what you are doing. We don't know, because we haven't got any code from you that creates that error.

If you want to write a data frame to a file, use write.table.

Upvotes: 9

Related Questions