Write CSV file with two columns in R loop (append) -
i have other complex script working fine, except giving trouble in writing csv file. let's here example want k , j here present in 20 rows, k being in 1 column , j being in second.
for (i in 1:20) { k = i+2; j = i+20; m= data.frame(k,j) write.csv(m,file="dummy.csv",append=true) print(m) }
the problem is, it writing final value of m csv, when append set true
and question here is, do need make 'm' dataframe, matrix or vector?
(consider k , j particular changing text strings, trying wite in csv extracting corpus)
the following output of csv file:
"","k","j" "1",22,40
you can't use append = true
write.csv
. idea should hard mess write.csv
, don't want to.
you can use write.table
, giving solution:
for (i in 1:20) { k = i+2; j = i+20; m = data.frame(k,j) write.table(m, file="dummy.csv", append=true, col.names = false, sep = ',') print(m) }
notice have miss out column names otherwise column names added in every iteration of loop.
but, better idea build dataframe in parts , write csv @ end.
m <- data.frame(null) (i in 1:20) { k <- i+2; j <- i+20; m <- rbind(m, data.frame(k,j)) } write.csv(m, file="dummy2.csv")
Comments
Post a Comment