查找符合特定条件的数据框中的最后一行 [英] Find the last row in a data frame that meets certain criteria
本文介绍了查找符合特定条件的数据框中的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种方法来引用数据帧中的一列,其中一列与当前行相同。基本上,如果这是我的数据框架
ABD
1 10
4 5
6 6
3 25
1 40
我想要D(i)以包含与A(i)具有相同值的最后一行的B值。所以最后一行应为10.
解决方案
您可以尝试
$($)
df1%>%
group_by(A)%>%
mutate(D =滞后(B))
#ABD
#1 1 10 NA
#2 4 5 NA
#3 6 6 NA
#4 3 25 NA
#5 1 40 10
或
code> library(data.table)#data.table_1.9.5
setDT(df1)[,D:= shift(B),A] []
数据
df1& (A = c(1L,4L,6L,3L,1L),B = c(10L,5L,6L,
25L,40L)).Names = c(A,B class =data.frame,
row.names = c(NA,-5L))
I'm looking for a way to refer to a pevious row in my data frame that has one column value in common with the 'current row'. Basically, if this would be my data frame
A B D
1 10
4 5
6 6
3 25
1 40
I would want D(i) to contain the B value of the last row for which A has the same value as A(i). So for the last row that should be 10.
解决方案
You may try
library(dplyr)
df1%>%
group_by(A) %>%
mutate(D=lag(B))
# A B D
#1 1 10 NA
#2 4 5 NA
#3 6 6 NA
#4 3 25 NA
#5 1 40 10
Or
library(data.table)#data.table_1.9.5
setDT(df1)[, D:=shift(B), A][]
data
df1 <- structure(list(A = c(1L, 4L, 6L, 3L, 1L), B = c(10L, 5L, 6L,
25L, 40L)), .Names = c("A", "B"), class = "data.frame",
row.names = c(NA, -5L))
这篇关于查找符合特定条件的数据框中的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文