문제

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?

도움이 되었습니까?

해결책

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

다른 팁

  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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top