Writing multiple values in different columns in a csv file in R

14,332

Make a dataframe and the write it.

y=test3[1,3:52]
 z=as.numeric(y) 
average = mean(z) 
st_dev = sd(z) }
 dfrm <- data.frame(average = average, st_dev = st_dev)
write.table(dfrm, file="z_st.csv", sep=",", row.names=FALSE, col.names=TRUE)

for(i in 2:130) { y=test3[i,3:52]
 z=as.numeric(y) 
average = mean(z) 
st_dev = sd(z) }
 dfrm <- data.frame(average = average, st_dev = st_dev)
write.table(dfrm, file="z_st.csv", sep=",", row.names=FALSE, col.names=FALSE)}
Share:
14,332
DianaHelen
Author by

DianaHelen

Updated on June 14, 2022

Comments

  • DianaHelen
    DianaHelen almost 2 years

    Can anyone help me with this: I have calculated 2 different values: standard deviation and z-scores.

    I'm trying to figure out how to write these into a csv file in different columns in R. I have about 90 different standard deviation values and 90 zscore values. So I want all my standard deviation values in 1 column and all my z-scores in the 2nd column. I also want to label the column with standard deviation and z-score.

    Right now I'm calculating and writing them into separate files in a loop like this:

    write.table(st_dev, file="st_dev.csv", sep=",", row.names=FALSE, col.names=FALSE, append=TRUE)
    write.table(z_score, file="z.csv", sep=",", row.names=FALSE, col.names=FALSE, append=TRUE)
    

    Edit:

    for(i in 1:130)
     {
     y=test3[i,3:52]
     z=as.numeric(y)
     average = mean(z)
     st_dev = sd(z)
     dfrm <- data.frame(average=average, st_dev=st_dev)
     write.table(dfrm, file="av_st.csv", sep=",", row.names=FALSE, col.names=TRUE, append=TRUE)
    }
    

    How can I have the column headers just once at the top instead of printing it for each value in the csv file? Thanks