I have a data frame ("res$data" in the example below), and I'd like to walk
through it, doing an approx() to interpolate each element in turn based on
the value of the item named "pressure" that is in the data.frame.
I've put some code below. I had hoped that the commented-out "length() <-"
line would let me adjust the lengths of the items, but that has no effect,
since I get an error that the replacement has 2 rows (correct, as I'm
testing this), although the data has 87 rows (again, that's the correct
value for the field upon which I'm doing the approx() interpolation.)
Q: is there a way I can change the length of an element in a data frame, so
that I can replace straight into it?
PS. the code doesn't know the names of the items in the data frame in
advance, although it is certain that one of them is called "pressure".
(This is an oceanographic application, in case anyone wonders why pressure
would be an independent variable for use in interpolation.)
<code>
#interpolate to target pressures in "pt".
npt <- length(pt)
for (datum.name in data.names) {
if (datum.name != "pressure") {
length(res$data[[datum.name]]) <- npt
res$data[[datum.name]] <- approx(x$data[["pressure"]],
x$data[[datum.name]], pt)$y
}
}
</code>
In case anyone with a similar need comes across this thread, I am posting
below a solution to my problem, in which I construct a new data frame that
has the desired dimensions, instead of trying to change the dimensions of
the existing data frame.
<code>
npt <- length(pt)
# Step through each variable.
data.names <- names(x$data)
data.new <- as.data.frame(array(NA, dim=c(npt, dim(x$data)[2])))
names(data.new) <- data.names
for (datum.name in data.names) {
if (datum.name != "pressure") {
data.new[[datum.name]] <- approx(x$data[["pressure"]],
x$data[[datum.name]], pt)$y
}
}
# Now replace pressure
data.new[["pressure"]] <- pt
res$data <- data.new
</code>