【发布时间】:2013-11-17 23:45:28
【问题描述】:
在 R 中,我遇到了一个与此处介绍的问题类似的问题:Replacing NAs in R with nearest value。然而,不同之处在于,我想要更改的值不是 NA,而是任何小于 0 的值,而且更改这些值取决于另一列中的值(因此需要添加条件语句)。我无法理解如何使该问题中提出的一些解决方案适应我的问题。这也很重要,因为我有很多数据。
样本数据
pred_trip <- c(0,0,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1)
locNumb <- c(-1,-1,-1,-1,-1,2,2,2,2,3,3,0,0,0,4,4,4,4,-1,-1,-1,-1,-1,0,0,0,0,0,0,5,5,5,5)
df <- data.frame(pred_trip, locNumb)
所以本质上,如果 locNumb 列中的值
期望的输出:
pred_trip locNumb
1 0 2
2 0 2
3 0 2
4 0 2
5 0 2
6 1 2
7 1 2
8 1 2
9 1 2
10 0 3
11 0 3
12 0 3
13 1 0
14 1 0
15 1 4
16 0 4
17 0 4
18 0 4
19 0 4
20 0 4
21 0 4
22 0 4
23 0 4
24 0 4
25 0 4
26 0 4
27 1 0
28 1 0
29 1 0
30 1 5
31 1 5
32 1 5
33 1 5
我无法在类似的解决方案中调整代码,因为它很大程度上依赖于 is.na,并且不包含我需要的任何其他条件。但是在伪代码中是这样的:(不确定在 if pred_trip == 0 的其他条件语句中添加的位置。
f1 <- function(df) {
N <- length(df)
na.pos <- which(df$locNumb < 0 (df))
if (length(na.pos) %in% c(0, N)) {
return(df)
}
non.na.pos <- which(!df$locNumb < 0(df))
intervals <- findInterval(na.pos, non.na.pos,
all.inside = TRUE)
left.pos <- non.na.pos[pmax(1, intervals)]
right.pos <- non.na.pos[pmin(N, intervals+1)]
left.dist <- na.pos - left.pos
right.dist <- right.pos - na.pos
df[na.pos] <- ifelse(left.dist <= right.dist,
df[left.pos], df[right.pos])
return(df)
}
【问题讨论】:
-
如果有 2 个最接近的值(负数之前和负数之后)大于 0,那么期望的输出是什么?
-
@geektrader,在这种情况下,负数(数字
-
如果
locNumbpre_trip 不 =0,会发生什么?我在您的示例数据中没有看到任何此类情况。您的实际应用程序中没有吗?如果没有,这会变得更简单。