Interpolate across row NA's of dataframe

时间:2018-07-25 04:27:48

标签: r dataframe interpolation na zoo

I have a dataframe with NA values peppered in that I want to interpolate.

Here is the repeatable example:

A <- as.data.frame(c(1:6))
A$b <- NA
A$c <- 2:7

library(zoo)
na.approx(A)

#expectation
A$b <- seq(1.5, 6.5, 1)

Obviously na.approx() isn't doing it for me, is there a function that will interpolate by row?

3 个答案:

答案 0 :(得分:6)

na.approx and also work column wise on a matrix

t(na.approx(t(A)))

答案 1 :(得分:3)

how about?

t(apply(A,1,na.approx));

答案 2 :(得分:0)

这里有一个解决方案,使您可以保留原始数据类型:

handleNearby = () => {
        const { region, providers } = this.state;
        let currentPoint = [region.longitude, region.latitude]
        let points = _.map(providers, p => {
            const to = [p.coordinates.longitude, p.coordinates.latitude];
            const distance = turf.distance(currentPoint, to, { units: 'kilometers' });
            return { coords: p.coordinates, name: p.username, id: p.id, service: p.service, distance }
        });
        const sortPoints = _.sortBy(points, ['distance']);
        this.setState({ sortedMarkers: sortPoints });
        return;
}

将明智地使用na.approx进行与上述解决方案相同的计算。 (但是通过这种方式,您仍将具有data.frame并保留您的列名)