I have a dataframe (check the picture). I am creating periods of 30 values and I am calculating how many of this values are over 0.1. At the end, I want to save all the 336 outputs in a dataframe (as a row). How could I do that? My code is failing!
i <- 0
secos=as.data.frame(NULL)
for (i in c(0:336)){
hola=as.data.frame(pp[c(1+i:29 + i)])
secos[[i]]=sum(hola > 0.1)
secos=rbind(secos[[i]])}
Iteratively building (growing) data.frame
s in R is a bad thing. For good reading, see the R Inferno , chapter 2 on Growing Objects . Bottom line, though: it works, but as you add more rows, it will get progressively slower and use (at least) twice as much memory as you intend.
You explicitly overwrite secos
with rbind(secos[[i]])
, where the rbind call is a complete no-op doing nothing. (eg, see identical(rbind(mtcars), mtcars)
). Back to (1), best to L <- lapply(0:336, function(i)...)
then secos <- do.call(rbind, L)
.
R indexes are 1-based, but your first call assigns to secos[[0]]
which fails.
A literal translation of this into a better start is something like the following. (Up front, your reference to pp
only makes sense if you have an object pp
that you used to create your data.frame
above... since pp[.]
by itself will not reference the frame. If you're using attach(.)
to be able to do that, then... don't. Too many risks and things that can go wrong with it, it is one of the base functions I'd vote to remove.)
invec <- 0:336
L <- sapply(invec, function(i) {
hola=as.data.frame(pp[c(1+i:29 + i)])
sum(hola > 0.1)
})
secos <- data.frame(i = invec, secos = L)
An alternative:
L <- lapply(invec, function(i) {
hola=as.data.frame(pp[c(1+i:29 + i)])
data.frame(secos = sum(hola > 0.1))
})
out <- do.call(rbind, L)
I can't help but think there is a more efficient, R- idiomatic way to aggregate this data. My guess is that it's a moving window of sorts, perhaps a month wide (or similar). If that's the case, I recommend looking into zoo::rollapply(pp, 30, function(z) sum(z > 0.1))
, perhaps with meaningful application of align=
, partial=
, and/or fill=
.
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.