Try na.locf from the zoo package and then use merge with specified suffixes:
library(zoo)
f - function(x) {
rownames(x) - NULL
merge(x, na.locf(x[-1], na.rm = FALSE), by = 0, suffixes = c(, .by))[-1]
}
do.call(rbind, by(x, x$id, f))
On 3/7/07, Jon Olav Vik [EMAIL PROTECTED] wrote:
Dear list,
Is there a way to programmatically specify tag names for the ... (ellipsis)
part of the argument list to a function? In other words, a way to do this:
x - data.frame(A=1:5)
if the name A was not hardcoded but given by a variable, and without
resorting to:
x - data.frame(1:5)
names(x) - A
A longer example describing my actual problem follows. Thanks in advance for
any help.
Best regards,
Jon Olav
I want to use function transformBy() in package doBy. The key is that the ...
Further arguments of the form tag=value require tag to be specified,
otherwise the output does not include the results of my groupwise
calculations.
Quoting the documentation:
transformBy(doBy)
Function to make groupwise transformations of data
by applying the transform function to subsets of data.
Usage
transformBy(formula, data, ...)
Arguments
formula A formula with only a right hand side, see examples below
data A data frame
... Further arguments of the form tag=value
### example ###
# a function to replace NAs with the last non-NA value from above
filldown - function(x) {
notna - !is.na(x) # elements with values
ix - cumsum(notna) # index to previous element (but zeros where we need
NA)
ix[ix==0] - NA # use [NA] as index to produce NA in output
return(x[notna][ix]) # for each: return previous value if found, else NA
}
# illustration of how it works
tmp - c(NA,NA,1,NA,3,NA,NA)
cbind(tmp,filldown(tmp))
# I now want to apply filldown() to subsets of a data frame
# and I want it to work on several columns
# generate a data frame for illustration,
# with a few non-NA values scattered round
set.seed(5) # repeatable example
x - data.frame(id = rep(1:4,each=6), v1=NA, v2=NA)
ix - which(runif(nrow(x))0.75)
x[ix,2] - rpois(length(ix),5)
ix - which(runif(nrow(x))0.75)
x[ix,3] - rpois(length(ix),5)
x
library(doBy)
# the hard way -- works as required,
# but I would like not having to hardcode column names v1 etc.
transformBy(~id,data=x,v1.fd = filldown(v1),v2.fd = filldown(v2))
# does not work because
# output includes only columns explicitly mentioned in the ... argument
transformBy(~id,data=x,function(y) lapply(y,filldown))
__
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
__
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.