简体   繁体   中英

Save a for loop in R

i want to save a for output

for (a in 2017:2018){

for (b in 1:12){
for (c in 1:30){
  
  RSM <- subset(RS,Ano==a & Mes==b & Dia==c)
  dime <- dim(RSM)
  tdia  = dime[c(1)]
  
}
}
}

i want to save tdia for each day each mont for 2017 and 2018 in a single csv. Any idea?

A general structure for saving a result from a loop can be something like:

result <- vector(length=N)

for(i in 1:N) {
    <do some things>
    result[i] <- <value to save>
}

You could then save the contents of result to a csv file if desired:

write.csv(result, file="filename.csv")

However, it seems like you are just trying to count the number of rows by your three date variables. Here's how I would do it (in one line:) with the data.table package:

library(data.table)
setDT(RS)

RS[ , .(num_de_filas=.N), by=.(Ano, Mes, Dia)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM