[18975] in s-news-athena
[S] summary: filling NA
daemon@ATHENA.MIT.EDU (fan@katan.cybercom.net)
Thu Aug 19 11:27:54 1999
From: fan@katan.cybercom.net
Date: Thu, 19 Aug 1999 11:20:29 -0400
Message-Id: <199908191520.LAA23188@katan.cybercom.net>
To: s-news@wubios.wustl.edu
Thanks for all so many responses! Below is the summary.
First of all, assume the first element is not NA or I
will fill in it with something sensible directly.
1.Most of the responses suggest using
x[which.na(x)] <- x[which.na(x)-1]
repeatedly, until all NA are filled. I.e.:
while(sum(is.na(x))>0) {x[which.na(x)] <- x[which.na(x)-1]}
This is efficient when the runs of NAs has a small length, as in my
datasets.
2.Bill Dunlap gives a function which is nice.
Though it takes me a while understand.
f2 <- function(x)
{
#if(!is.logical(x)) stop("x must be a logical vector")
#if(x[1]) stop("First element of x must not be TRUE")
val <- seq(along = x)
val[x] <- 0
val[!x][-1] <- diff(val[!x])
cumsum(val)
}
With that function you can solve the problem with
x <- x[f2(is.na(x))]
Note: x[1] must not be NA, otherwise error occurs
At last: this question naturally generalize to the cases of substituting
other kinds of abnormal numbers, not just NAs. In that case, change
"is.na(x)" to an appropriate test, such as "x==0", "x <= 0", etc.
Good luck.
Fan
[original message]
"x" is a vector with NA's in it. I want to fill in these missing values and
choose to fill in the number immediately antecedent to it. For example,
> x
[1] 1.728207 NA 2.687416 4.152794 NA NA 6.879287 6.825644
[9] 7.729189 9.689368
I will fill in x[2] with x[1], fill in x[5] and x[6] with x[4], the result
should be
> x
[1] 1.728207 1.728207 2.687416 4.152794 4.152794 4.152794 6.879287 6.825644
[9] 7.729189 9.689368
Is there a way to work on this with S vector operations? I.e., somethings more
concise while having the same effect as the lengthy codes below:
current <- x[1] #assuming x[1] is not
for (i in 1:length(x))
if(x[i]=="NA")
x[i] <- current
else
current <- x[i]
}
Thanks
Fan
-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news