In data frame: writing to file and assigning associated vector in R
I have data that looks like this . And my code below is just to compute some value and bind 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 a couple of questions regarding the above:
-
But why is the 'write ()' function above giving this error. Is there a way to fix this?
Error in cat (list (...), file, sep, fill, labels, append): argument 1 (type "list") cannot be processed "cat" Calls: write -> cat Execution paused
-
Anchored vector names in the dataframe are added as "errprob" for all 10 new columns. Is there a way to name them like "errprob1", "errprob2", etc.?
source to share
First, there is no need for half-columns, 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)
-
I believe you are looking for the write.table function
-
Use colnames function
source to share
-
You can use write.table () instead of write () for use with the above arguments. The latter is fine for printing matrices (but may require ncol or transpose the input matrix), but the former is more general and I use it for both matrices and data frames.
-
You can replace
err_prob <- pnorm (dat $ V4, mean = meanl, sd = stdevl)
problist <- cbind (problist, err_prob)
from
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 also do
colnames(problist) <- sprintf("err_prob%d",1:10)
a posteriori
source to share