101

从这样的数据框

test <- data.frame('id'= rep(1:5,2), 'string'= LETTERS[1:10])
test <- test[order(test$id), ]
rownames(test) <- 1:10

> test
    id string
 1   1      A
 2   1      F
 3   2      B
 4   2      G
 5   3      C
 6   3      H
 7   4      D
 8   4      I
 9   5      E
 10  5      J

我想用每个 id / string 对的第一行创建一个新的。如果 sqldf 接受其中的 R 代码,则查询可能如下所示:

res <- sqldf("select id, min(rownames(test)), string 
              from test 
              group by id, string")

> res
    id string
 1   1      A
 3   2      B
 5   3      C
 7   4      D
 9   5      E

是否有没有像创建新列这样的解决方案

test$row <- rownames(test)

并使用 min(row) 运行相同的 sqldf 查询?

4

7 回答 7

129

您可以使用duplicated它非常快速地执行此操作。

test[!duplicated(test$id),]

基准,对于速度怪胎:

ju <- function() test[!duplicated(test$id),]
gs1 <- function() do.call(rbind, lapply(split(test, test$id), head, 1))
gs2 <- function() do.call(rbind, lapply(split(test, test$id), `[`, 1, ))
jply <- function() ddply(test,.(id),function(x) head(x,1))
jdt <- function() {
  testd <- as.data.table(test)
  setkey(testd,id)
  # Initial solution (slow)
  # testd[,lapply(.SD,function(x) head(x,1)),by = key(testd)]
  # Faster options :
  testd[!duplicated(id)]               # (1)
  # testd[, .SD[1L], by=key(testd)]    # (2)
  # testd[J(unique(id)),mult="first"]  # (3)
  # testd[ testd[,.I[1L],by=id] ]      # (4) needs v1.8.3. Allows 2nd, 3rd etc
}

library(plyr)
library(data.table)
library(rbenchmark)

# sample data
set.seed(21)
test <- data.frame(id=sample(1e3, 1e5, TRUE), string=sample(LETTERS, 1e5, TRUE))
test <- test[order(test$id), ]

benchmark(ju(), gs1(), gs2(), jply(), jdt(),
    replications=5, order="relative")[,1:6]
#     test replications elapsed relative user.self sys.self
# 1   ju()            5    0.03    1.000      0.03     0.00
# 5  jdt()            5    0.03    1.000      0.03     0.00
# 3  gs2()            5    3.49  116.333      2.87     0.58
# 2  gs1()            5    3.58  119.333      3.00     0.58
# 4 jply()            5    3.69  123.000      3.11     0.51

让我们再试一次,但只有第一场比赛的竞争者,更多的数据和更多的复制。

set.seed(21)
test <- data.frame(id=sample(1e4, 1e6, TRUE), string=sample(LETTERS, 1e6, TRUE))
test <- test[order(test$id), ]
benchmark(ju(), jdt(), order="relative")[,1:6]
#    test replications elapsed relative user.self sys.self
# 1  ju()          100    5.48    1.000      4.44     1.00
# 2 jdt()          100    6.92    1.263      5.70     1.15
于 2012-11-07T23:12:54.090 回答
64

我赞成 dplyr 方法。

group_by(id)其次是

  • filter(row_number()==1)或者
  • slice(1)或者
  • slice_head(1) #(dplyr => 1.0)
  • top_n(n = -1)
    • top_n()内部使用 rank 函数。负数从排名的底部选择。

在某些情况下,可能需要在 group_by 之后安排 id。

library(dplyr)

# using filter(), top_n() or slice()

m1 <-
test %>% 
  group_by(id) %>% 
  filter(row_number()==1)

m2 <-
test %>% 
  group_by(id) %>% 
  slice(1)

m3 <-
test %>% 
  group_by(id) %>% 
  top_n(n = -1)

所有三种方法都返回相同的结果

# A tibble: 5 x 2
# Groups:   id [5]
     id string
  <int> <fct> 
1     1 A     
2     2 B     
3     3 C     
4     4 D     
5     5 E
于 2018-06-20T18:43:04.247 回答
18

关于什么

DT <- data.table(test)
setkey(DT, id)

DT[J(unique(id)), mult = "first"]

编辑

还有一个独特的方法,data.tables它将按键返回第一行

jdtu <- function() unique(DT)

我认为,如果您test在基准之外订购,那么您也可以从基准中删除setkeyanddata.table转换(因为 setkey 基本上按 id 排序,与 相同order)。

set.seed(21)
test <- data.frame(id=sample(1e3, 1e5, TRUE), string=sample(LETTERS, 1e5, TRUE))
test <- test[order(test$id), ]
DT <- data.table(DT, key = 'id')
ju <- function() test[!duplicated(test$id),]

jdt <- function() DT[J(unique(id)),mult = 'first']


 library(rbenchmark)
benchmark(ju(), jdt(), replications = 5)
##    test replications elapsed relative user.self sys.self 
## 2 jdt()            5    0.01        1      0.02        0        
## 1  ju()            5    0.05        5      0.05        0         

并且有更多的数据

**用独特的方法编辑**

set.seed(21)
test <- data.frame(id=sample(1e4, 1e6, TRUE), string=sample(LETTERS, 1e6, TRUE))
test <- test[order(test$id), ]
DT <- data.table(test, key = 'id')
       test replications elapsed relative user.self sys.self 
2  jdt()            5    0.09     2.25      0.09     0.00    
3 jdtu()            5    0.04     1.00      0.05     0.00      
1   ju()            5    0.22     5.50      0.19     0.03        

独特的方法在这里最快。

于 2012-11-08T00:12:09.793 回答
14

一个简单的ddply选择:

ddply(test,.(id),function(x) head(x,1))

如果速度是一个问题,可以采用类似的方法data.table

testd <- data.table(test)
setkey(testd,id)
testd[,.SD[1],by = key(testd)]

或者这可能会更快:

testd[testd[, .I[1], by = key(testd]$V1]
于 2012-11-07T22:50:49.943 回答
10

现在,对于dplyr,添加一个不同的计数器。

df %>%
    group_by(aa, bb) %>%
    summarise(first=head(value,1), count=n_distinct(value))

您创建组,它们在组内进行汇总。

如果数据是数字,您可以使用:
first(value)[there is also last(value)] 代替head(value, 1)

见: http ://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html

满的:

> df
Source: local data frame [16 x 3]

   aa bb value
1   1  1   GUT
2   1  1   PER
3   1  2   SUT
4   1  2   GUT
5   1  3   SUT
6   1  3   GUT
7   1  3   PER
8   2  1   221
9   2  1   224
10  2  1   239
11  2  2   217
12  2  2   221
13  2  2   224
14  3  1   GUT
15  3  1   HUL
16  3  1   GUT

> library(dplyr)
> df %>%
>   group_by(aa, bb) %>%
>   summarise(first=head(value,1), count=n_distinct(value))

Source: local data frame [6 x 4]
Groups: aa

  aa bb first count
1  1  1   GUT     2
2  1  2   SUT     2
3  1  3   SUT     3
4  2  1   221     3
5  2  2   217     3
6  3  1   GUT     2
于 2014-07-29T12:03:18.090 回答
7

(1) SQLite 有一个内置的rowid伪列,所以这有效:

sqldf("select min(rowid) rowid, id, string 
               from test 
               group by id")

给予:

  rowid id string
1     1  1      A
2     3  2      B
3     5  3      C
4     7  4      D
5     9  5      E

(2)sqldf本身也有row.names=论据:

sqldf("select min(cast(row_names as real)) row_names, id, string 
              from test 
              group by id", row.names = TRUE)

给予:

  id string
1  1      A
3  2      B
5  3      C
7  4      D
9  5      E

(3) 混合上述两种元素的第三种选择可能会更好:

sqldf("select min(rowid) row_names, id, string 
               from test 
               group by id", row.names = TRUE)

给予:

  id string
1  1      A
3  2      B
5  3      C
7  4      D
9  5      E

请注意,所有这三个都依赖于 SQL 的 SQLite 扩展,其中使用minormax保证会导致从同一行中选择其他列。(在其他可能无法保证的基于 SQL 的数据库中。)

于 2012-11-08T17:15:38.603 回答
5

基本 R 选项是split()- lapply()-do.call()成语:

> do.call(rbind, lapply(split(test, test$id), head, 1))
  id string
1  1      A
2  2      B
3  3      C
4  4      D
5  5      E

更直接的选择是lapply()函数[

> do.call(rbind, lapply(split(test, test$id), `[`, 1, ))
  id string
1  1      A
2  2      B
3  3      C
4  4      D
5  5      E

1, )调用结束时的逗号空格lapply()必不可少的,因为这相当于调用[1, ]选择第一行和所有列。

于 2012-11-07T22:56:41.263 回答