views:

531

answers:

2

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?

+2  A: 
  1. You can use write.table() instead of write() to use with the arguments specified above. The latter is suited for printing matrices (but may require specifying ncol or transposing the input matrix) but the former is more general and I use it for both matrices and data frames.

  2. You can replace

    err_prob <- pnorm(dat$V4,mean=meanl, sd=stdevl)

    problist <- cbind(problist,err_prob)

with

assign(sprintf("err_prob%d",lmer),pnorm(dat$V4,mean=meanl, sd=stdevl))
problist <- eval(parse(text=sprintf("cbind(problist,err_prob%d)", lmer)))

The last line parses the character string as an expression and then evaluates it. You can alternatively do

colnames(problist) <- sprintf("err_prob%d",1:10)

a posteriori

Stephen
+2  A: 
Ian Fellows
It is always best to create the matrix beforehand. `problist <- matrix(NA, ncol=10, nrow=200) and then problist[,lmer] <- err_prob.
Eduardo Leoni