On Data Frame: Writing to File and Naming Binded Vector in R

neversaint picture neversaint · Sep 4, 2009 · Viewed 11.4k times · Source

I have a data that looks like this. And my code below simply compute some value and binds the output vector to the original data frames.

options(width=200)

args<-commandArgs(trailingOnly=FALSE)
dat <- read.table("http://dpaste.com/89376/plain/",fill=T);

problist <- c();

for (lmer in 1:10) {
   meanl <- lmer;
   stdevl <- (0.17*sqrt(lmer));
   err_prob <- pnorm(dat$V4,mean=meanl, sd=stdevl);
   problist <- cbind(problist,err_prob);
}

dat <- cbind(dat,problist)
#print(dat,row.names=F, column.names=F,justify=left)

# Why this breaks?
write(dat, file="output.txt", sep="\t",append=F);

I have couple of questions regarding the above:

  1. But why the 'write()' function above gives this error. Is there a way to fix it?

    Error in cat(list(...), file, sep, fill, labels, append) : argument 1 (type 'list') cannot be handled by 'cat' Calls: write -> cat Execution halted

  2. Names for binded vector in the data frame is added as "errprob" for all 10 new columns. Is there a way to name them like "errprob1", "errprob2", etc?

Answer

Ian Fellows picture Ian Fellows · Sep 4, 2009

First off, no need for the semi-colons, R knows that the end of the line is a break.


for (lmer in 1:10){
    meanl <- lmer
    stdevl <- (0.17*sqrt(lmer))
    err_prob <- pnorm(dat$V4,mean=meanl, sd=stdevl)
    problist <- cbind(problist,err_prob)
}
colnames(problist)<-paste("errorprob",1:10,sep="")
dat <- cbind(dat,problist)
write.table(dat, file="output.txt", sep="\t",append=F)

  1. I believe that you are looking for the write.table function

  2. Use the colnames function