我有两个向量,数据x和y,第一个是距离,第二个是温度。
如何从x和y两个连续点之间移除距离较低的所有点( xi - xi-1 )
x = (1,2,3,8,12)
y = (10,12,11,9,12)移除距离小于5的点
x = 1, 2(out as 2-1 <5), 3 (out as 3-1 <5), 8, 12 (fine as last even thoug 12-8<5)
x = (1,8,12)
y = (10,9,12)发布于 2017-08-22 12:17:39
这里有一个假设您的第一个和最后一个元素从未被移除的想法,
v1 <- setNames(x, y)[c(TRUE, (diff(x) >= 5)[-(length(x)-1)], TRUE)]
#10 9 12
# 1 8 12
#To make it a bit more clear on how the named vector is structured (still a vector)
names(v1)
#[1] "10" "9" "12" <- Note: I get 9 whereas you get 11
unname(v1)
#[1] 1 8 12或者你可以把它变成一个函数,
rm_elements <- function(x, y, n){
v1 <- setNames(x, y)[c(TRUE, (diff(x) >= n)[-(length(x)-1)], TRUE)]
return(list(x = unname(v1), y = as.numeric(names(v1))))
}
rm_elements(x, y, 5)
#$x
#[1] 1 8 12
#$y
#[1] 10 9 12编辑:为了容纳您的注释,当您在数据帧中使用它们时,我们可以稍微修改函数以接受数据框架(无论您如何命名变量),并返回该数据框架的子集,即
rm_elements <- function(df, n){
v1 <- df[c(TRUE, (diff(df[[1]]) >= n)[-(nrow(df)-1)], TRUE),]
return(v1)
}
#Make a data frame from the vectors,
d1 <- data.frame(x=x, y=y)
rm_elements(d1, 5)这给了,
x y 1 1 10 4 8 9 5 12 12
https://stackoverflow.com/questions/45816507
复制相似问题