If you are worried about an NA in the first, then use the following:
> y <- c(NA, 1, 2, NA, 4, NA)
> y <- na.locf(y, na.rm = FALSE)
> y
[1] NA 1 2 2 4 4
> y <- na.locf(y, fromLast = TRUE)
> y
[1] 1 1 2 2 4 4
>
On Mon, Jan 2, 2012 at 5:07 PM, Joshua Wiley wrote:
> Good points, Rui.
>
> On M
Good points, Rui.
On Mon, Jan 2, 2012 at 12:48 PM, Rui Barradas wrote:
> Hello again,
>
> I believe we are all missing something. Isn't it possible to have NAs as the
> first values of 'y'?
> And isn't it also possible to have x[1] > 3?
Theoretically, yes, in the OPs data, maybe? If the data is
Hello again,
I believe we are all missing something. Isn't it possible to have NAs as the
first values of 'y'?
And isn't it also possible to have x[1] > 3?
Here is my point (I have changed function 'f2' to predict for such cases,
'f1' is rubbish)
# Rui
f3 <- function(x, y){
inx <- which(
Here is a way of doing it without loops:
> df <- data.frame(x = c(1,2,3,4,5), y = c(10,20,30,NA,NA))
>
> require(zoo) # need na.locf to fix the NAs
>
> # replace NA with preceeding values
> df$y <- na.locf(df$y)
> df
x y
1 1 10
2 2 20
3 3 30
4 4 30
5 5 30
>
> # assuming that you want to increm
Here is another approach. Probably with some thought and fingerwork,
rle() could be used to avoid the while loop, but that should only slow
things down if there are long runs of NAs --- there can be a lot of
NAs as long as they are spaced apart and it should still be quite
efficient.
f <- functio
I am trying to add a constant to the previous value of a variable based on
certain conditions. Maybe there is a simple way to do this that I am missing
completely. I have given an example below:
df <- data.frame(x = c(1,2,3,4,5), y = c(10,20,30,NA,NA))
> df
x y
1 1 10
2 2 20
3 3 30
4 4 NA
5 5
Hello,
I believe this works.
f1 <- function(x){
for(i in 2:length(x)) x[i] <- ifelse(x[i-1] > 3, x[i-1] + 2, x[i])
x
}
f2 <- function(x){
for(i in 2:length(x)) x[i] <- ifelse(is.na(x[i]) & (x[i-1] > 3), x[i-1]
+
2, x[i])
x
}
df <- data.frame(x = c(1,2,3,4,5), y
7 matches
Mail list logo