Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 无循环索引相邻值_R_Loops - Fatal编程技术网

R 无循环索引相邻值

R 无循环索引相邻值,r,loops,R,Loops,我喜欢从data.frame中平均出比相邻帧小的值。例如: df <- data.frame(V1 = c(1:10), V2 = c(0.5, 1, 2, 6, 7, 6.5, 8, 8.2, 8.1, 8.5)) for (i in 2:(nrow(df)-1)) { df[i,2] <- ifelse( df[i,2] < df[i+1,2] & df[i,2] < df[i-1,2], mean(c(df[i+1,

我喜欢从data.frame中平均出比相邻帧小的值。例如:

 df <- data.frame(V1 = c(1:10), V2 = c(0.5, 1, 2, 6, 7, 6.5, 8, 8.2, 8.1, 8.5))

 for (i in 2:(nrow(df)-1)) {
    df[i,2] <- ifelse( 
      df[i,2] < df[i+1,2] & df[i,2] < df[i-1,2], 
      mean(c(df[i+1,2], df[i-1,2])), 
      df[i,2]
    )
 }
df我们可以试试

 i1 <- c(FALSE, (df$V2[-nrow(df)] - df$V2[-1])>0 & (df$V2[-1] - df$V2[-nrow(df)]) < 0)

df$V2[i1] <- sapply(which(i1), function(i) mean(df$V2[c(i-1,i+1)]))
df$V2
#[1] 0.50 1.00 2.00 6.00 7.00 7.50 8.00 8.20 8.35 8.50
我们可以试试

 i1 <- c(FALSE, (df$V2[-nrow(df)] - df$V2[-1])>0 & (df$V2[-1] - df$V2[-nrow(df)]) < 0)

df$V2[i1] <- sapply(which(i1), function(i) mean(df$V2[c(i-1,i+1)]))
df$V2
#[1] 0.50 1.00 2.00 6.00 7.00 7.50 8.00 8.20 8.35 8.50

您可以通过矢量化执行此操作:

inds <- which(with(df, V2<c(NA,head(V2,-1)) & V2<c(tail(V2,-1),NA)))
#[1] 6 9

df$V2[inds] <- (df$V2[inds-1]+df$V2[inds+1])/2

   # V1   V2
# 1   1 0.50
# 2   2 1.00
# 3   3 2.00
# 4   4 6.00
# 5   5 7.00
# 6   6 7.50
# 7   7 8.00
# 8   8 8.20
# 9   9 8.35
# 10 10 8.50

inds您可以通过矢量化:

inds <- which(with(df, V2<c(NA,head(V2,-1)) & V2<c(tail(V2,-1),NA)))
#[1] 6 9

df$V2[inds] <- (df$V2[inds-1]+df$V2[inds+1])/2

   # V1   V2
# 1   1 0.50
# 2   2 1.00
# 3   3 2.00
# 4   4 6.00
# 5   5 7.00
# 6   6 7.50
# 7   7 8.00
# 8   8 8.20
# 9   9 8.35
# 10 10 8.50
inds
i1
i1