[英]Aggregate strings on the basis of a column in R, keep only first/last
我有一個像這樣的虛擬數據集:
x y
1 1 test1
2 2 test2
3 2 test3
4 3 test4
5 3 test5
我想基於x
中的值對其進行匯總,而不是連接或運行最大頻率檢查,而只是想顯示該x
值的最后一個/第一個值(基於行號)。 我想知道如何顯示最后一個值和第一個值。 簡單地刪除基於x
重復項將不會給我提供選擇y
值的靈活性。
我的輸出將是這樣(最后):
x y
1 1 test1
2 2 test3
3 3 test5
或像這樣(第一個):
x y
1 1 test1
2 2 test2
3 3 test4
我有1M +行的大型數據集。 幫助將不勝感激。 我試過聚合和ddply方法。
您可以使用dplyr::distinct()
,它根據變量保留唯一行,如果將.keep_all
參數指定為TRUE
,則將為指定變量的每個不同值獲得第一行:
獲得第一個:
library(dplyr)
df %>%
distinct(x, .keep_all = TRUE)
# x y
#1 1 test1
#2 2 test2
#3 3 test4
要獲得最后一行,您可以通過按行降序對row_number()
進行排序,然后使用distinct()
來反轉數據框:
df %>%
arrange(desc(row_number())) %>%
distinct(x, .keep_all = TRUE)
# x y
#1 3 test5
#2 2 test3
#3 1 test1
您可以使用duplicated
df[!duplicated(df$x, fromLast=TRUE),]
x y
1 1 test1
3 2 test3
5 3 test5
df[!duplicated(df$x),]
x y
1 1 test1
2 2 test2
4 3 test4
另外,您可以使用data.table
因為您說的數據非常大。 我給出了兩個示例,每個第一個/最后一個值都給出相同的結果。 使用setkey
的方法將更快。
library(data.table)
第一價值
方法1:
dt[dt[,list(keep=.I[which.min(.I)]),by=.(x)][,keep]]
方法2:
setkey(dt,x)
dt[J(unique(x)),mult="first"]
x y
1: 1 test1
2: 2 test2
3: 3 test4
最后值
方法1:
dt[dt[,list(keep=.I[which.max(.I)]),by=.(x)][,keep]]
方法2:
setkey(dt,x)
dt[J(unique(x)),mult="last"]
x y
1: 1 test1
2: 2 test3
3: 3 test5
數據
dt <- structure(list(x = c(1L, 2L, 2L, 3L, 3L), y = structure(1:5, .Label = c("test1",
"test2", "test3", "test4", "test5"), class = "factor")), .Names = c("x",
"y"), class = c("data.table", "data.frame"), row.names = c(NA,
-5L), .internal.selfref = <pointer: 0x0000000000140788>)
編輯 :在setkey()
方法中添加。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.