R:查找具有非唯一/重复值的数据框索引



我想从向量中提取一些值,修改它们并将它们放回原始位置。
我一直在寻找很多,并尝试了不同的方法来解决这个问题。恐怕这可能非常简单,但我还没有看到它。


创建矢量并将其转换为数据帧。还为结果创建一个空数据框。

hight <- c(5,6,1,3)
hight_df <- data.frame("ID"=1:length(hight), "hight"=hight)
hight_min_df <- data.frame()

为每对值提取具有相应 ID 的较小值。

for(i in 1:(length(hight_df[,2])-1))
{
hight_min_df[i,1] <- which(grepl(min(hight_df[,2][i:(i+1)]), hight_df[,2]))
hight_min_df[i,2] <- min(hight_df[,2][i:(i+1)])
}

修改提取的值,并通过更高的值聚合相同的 ID。最后写回修改后的值。

hight_min_df[,2] <- hight_min_df[,2]+20  
adj_hight <- aggregate(x=hight_min_df[,2],by=list(hight_min_df[,1]), FUN=max)
hight[adj_hight[,1]] <- adj_hight[,2]

只要我在hight中只有 uniqe 值,这就可以完美地工作。 如何使用这样的向量运行此脚本:hight <- c(5,6,1,3,5)

好吧,这里有很多东西要解开。与其循环,我建议使用dplyr管道函数。在此处阅读小插图 - 这是一个出色的资源,也是在 R 中操作数据的绝佳方法。

因此,使用dplyr我们可以像这样重写您的代码:

library(dplyr)
hight <- c(5,6,1,3,5) #skip straight to the test case
hight_df <- data.frame("ID"=1:length(hight), "hight"=hight)
adj_hight <- hight_df %>%
#logic psuedo code: if the last hight (using lag() function),
# going from the first row to the last,
# is greater than the current rows hight, take the current rows value. else
# take the last rows value
mutate(subst.id = ifelse(lag(hight) > hight, ID, lag(ID)), 
subst.val = ifelse(lag(hight) > hight, hight, lag(hight)) + 20) %>%
filter(!is.na(subst.val)) %>% #remove extra rows
select(subst.id, subst.val) %>% #take just the columns we want
#grouping - rewrite of your use of aggregate
group_by(subst.id) %>% 
summarise(subst.val = max(subst.val)) %>%
data.frame(.)
#tying back in
hight[adj_hight[,1]] <- adj_hight[,2]
print(hight)

给:

[1] 25  6 21 23  5

相关内容

最新更新