为另一列的每个唯一值提取包含第一个值的所有行 [英] Extract all rows containing first value for each unique value of another column
问题描述
我正在寻找与此类似的东西 R 中列的每个唯一值仅选择第一行但我需要保留包含每个 ID 年份的第一个值的所有行.换句话说,我需要按个人 ID 对列出的第一年的数据集进行子集化.ID 可以有他们的第一个1 2 或 3 中的年份,并且应保留第一年的所有行.例如:
I am looking for something similar to this Select only the first rows for each unique value of a column in R but I need to keep ALL rows containing the first values of year per ID. In ither words, I need to subset the dataset on the first year listed, by individual ID. IDs can have their first year in 1 2 or 3, and all of the rows in the first year should be retained. For example:
ID <- c("54V", "54V", "54V", "54V", "56V", "56V", "56V", "59V", "59V", "59V")
yr <- c(1, 1, 1, 2, 2, 2, 3, 1, 2, 3)
test <- data.frame(ID,yr)
test
ID yr
1 54V 1
2 54V 1
3 54V 1
4 54V 2
5 56V 2
6 56V 2
7 56V 3
8 59V 1
9 59V 2
10 59V 3
预期结果:
ID yr
1 54V 1
2 54V 1
3 54V 1
4 56V 2
5 56V 2
6 59V 1
我的数据集有很多列,我需要保留所有列.在 R 中使用 R 或 sqldf 的任何说明都有帮助!
My dataset has many columns and I need to retain them all. Any directions with R or sqldf in R are helpful!
推荐答案
我们可以用 dplyr
library(dplyr)
test %>%
group_by(ID) %>%
filter(yr==first(yr))
# ID yr
# <fctr> <dbl>
#1 54V 1
#2 54V 1
#3 54V 1
#4 56V 2
#5 56V 2
#6 59V 1
<小时>
或者使用data.table
library(data.table)
setDT(test)[, .SD[yr==yr[1L]], ID]
<小时>
或者使用 base R
test[with(test, as.logical(ave(yr, ID, FUN = function(x) x==x[1L]))),]
这篇关于为另一列的每个唯一值提取包含第一个值的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!