对数据框中组内的行进行编号

时间:2012-10-16 23:38:42

标签: r dataframe r-faq

使用与此类似的数据框:

set.seed(100)  
df <- data.frame(cat = c(rep("aaa", 5), rep("bbb", 5), rep("ccc", 5)), val = runif(15))             
df <- df[order(df$cat, df$val), ]  
df  

   cat        val  
1  aaa 0.05638315  
2  aaa 0.25767250  
3  aaa 0.30776611  
4  aaa 0.46854928  
5  aaa 0.55232243  
6  bbb 0.17026205  
7  bbb 0.37032054  
8  bbb 0.48377074  
9  bbb 0.54655860  
10 bbb 0.81240262  
11 ccc 0.28035384  
12 ccc 0.39848790  
13 ccc 0.62499648  
14 ccc 0.76255108  
15 ccc 0.88216552 

我正在尝试在每个组中添加一个带编号的列。这样做显然不是使用R的力量:

 df$num <- 1  
 for (i in 2:(length(df[,1]))) {  
   if (df[i,"cat"]==df[(i-1),"cat"]) {  
     df[i,"num"]<-df[i-1,"num"]+1  
     }  
 }  
 df  

   cat        val num  
1  aaa 0.05638315   1  
2  aaa 0.25767250   2  
3  aaa 0.30776611   3  
4  aaa 0.46854928   4  
5  aaa 0.55232243   5  
6  bbb 0.17026205   1  
7  bbb 0.37032054   2  
8  bbb 0.48377074   3  
9  bbb 0.54655860   4  
10 bbb 0.81240262   5  
11 ccc 0.28035384   1  
12 ccc 0.39848790   2  
13 ccc 0.62499648   3  
14 ccc 0.76255108   4  
15 ccc 0.88216552   5  

这样做的好方法是什么?

9 个答案:

答案 0 :(得分:206)

使用aveddplydplyrdata.table

df$num <- ave(df$val, df$cat, FUN = seq_along)

或:

library(plyr)
ddply(df, .(cat), mutate, id = seq_along(val))

或:

library(dplyr)
df %>% group_by(cat) %>% mutate(id = row_number())

或(内存效率最高,因为它在DT内通过引用分配):

library(data.table)
DT <- data.table(df)

DT[, id := seq_len(.N), by = cat]
DT[, id := rowid(cat)]

答案 1 :(得分:22)

为了使问题更加完整,使用sequencerle的基础R替代方案:

df$num <- sequence(rle(df$cat)$lengths)

给出了预期的结果:

> df
   cat        val num
4  aaa 0.05638315   1
2  aaa 0.25767250   2
1  aaa 0.30776611   3
5  aaa 0.46854928   4
3  aaa 0.55232243   5
10 bbb 0.17026205   1
8  bbb 0.37032054   2
6  bbb 0.48377074   3
9  bbb 0.54655860   4
7  bbb 0.81240262   5
13 ccc 0.28035384   1
14 ccc 0.39848790   2
11 ccc 0.62499648   3
15 ccc 0.76255108   4
12 ccc 0.88216552   5

如果df$cat是因子变量,则需要首先将其包装在as.character中:

df$num <- sequence(rle(as.character(df$cat))$lengths)

答案 2 :(得分:7)

这是一个选项,使用for循环按组而不是行(如OP所做的)

for (i in unique(df$cat)) df$num[df$cat == i] <- seq_len(sum(df$cat == i))

答案 3 :(得分:5)

我想使用with your_table (tran_type) as ( select 'success' from dual union all select 'failed' from dual union all select '123456-001' from dual union all select '654321-001' from dual union all select '098765-002' from dual union all select 'time out' from dual ) select tran_type from your_table where regexp_like(tran_type, '^\d{6}-\d{3}$'); TRAN_TYPE ---------- 123456-001 654321-001 098765-002 函数添加data.table变体,这提供了更改排序的额外可能性,从而使其比rank()解决方案更灵活,并且非常类似于RDBMS中的row_number函数。

seq_len()

答案 4 :(得分:4)

这是一个小的改进技巧,允许在组内排序“ val”:

# 1. Data set
set.seed(100)
df <- data.frame(
  cat = c(rep("aaa", 5), rep("ccc", 5), rep("bbb", 5)), 
  val = runif(15))             

# 2. 'dplyr' approach
df %>% 
  arrange(cat, val) %>% 
  group_by(cat) %>% 
  mutate(id = row_number())

答案 5 :(得分:1)

另一种dplyr可能是:

df %>%
 group_by(cat) %>%
 mutate(num = 1:n())

   cat      val   num
   <fct>  <dbl> <int>
 1 aaa   0.0564     1
 2 aaa   0.258      2
 3 aaa   0.308      3
 4 aaa   0.469      4
 5 aaa   0.552      5
 6 bbb   0.170      1
 7 bbb   0.370      2
 8 bbb   0.484      3
 9 bbb   0.547      4
10 bbb   0.812      5
11 ccc   0.280      1
12 ccc   0.398      2
13 ccc   0.625      3
14 ccc   0.763      4
15 ccc   0.882      5

答案 6 :(得分:1)

rowid()中使用data.table函数:

> set.seed(100)  
> df <- data.frame(cat = c(rep("aaa", 5), rep("bbb", 5), rep("ccc", 5)), val = runif(15))
> df <- df[order(df$cat, df$val), ]  
> df$num <- data.table::rowid(df$cat)
> df
   cat        val num
4  aaa 0.05638315   1
2  aaa 0.25767250   2
1  aaa 0.30776611   3
5  aaa 0.46854928   4
3  aaa 0.55232243   5
10 bbb 0.17026205   1
8  bbb 0.37032054   2
6  bbb 0.48377074   3
9  bbb 0.54655860   4
7  bbb 0.81240262   5
13 ccc 0.28035384   1
14 ccc 0.39848790   2
11 ccc 0.62499648   3
15 ccc 0.76255108   4
12 ccc 0.88216552   5

答案 7 :(得分:1)

另一种基础R解决方案将是splitcat lapply个数据帧,之后使用1:nrow(x):添加编号为{{1}的列}。最后一步是用do.call返回最后一个数据帧,即:

        df_split <- split(df, df$cat)
        df_lapply <- lapply(df_split, function(x) {
          x$num <- seq_len(nrow(x))
          return(x)
        })
        df <- do.call(rbind, df_lapply)

答案 8 :(得分:1)

非常简单、整洁的解决方案。

整个 data.frame 的行号

library(tidyverse)

iris %>%
  mutate(row_num = seq_along(Sepal.Length)) %>%
  head

    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species row_num
1            5.1         3.5          1.4         0.2     setosa       1
2            4.9         3.0          1.4         0.2     setosa       2
3            4.7         3.2          1.3         0.2     setosa       3
..           ...         ...          ...         ...     ......     ...
148          6.5         3.0          5.2         2.0  virginica     148
149          6.2         3.4          5.4         2.3  virginica     149
150          5.9         3.0          5.1         1.8  virginica     150

data.frame 中按组划分的行数

iris %>% 
  group_by(Species) %>% 
  mutate(num_in_group=seq_along(Species)) %>% 
  as.data.frame


    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species num_in_group
1            5.1         3.5          1.4         0.2     setosa            1
2            4.9         3.0          1.4         0.2     setosa            2
3            4.7         3.2          1.3         0.2     setosa            3
..           ...         ...          ...         ...     ......           ..
48           4.6         3.2          1.4         0.2     setosa           48
49           5.3         3.7          1.5         0.2     setosa           49
50           5.0         3.3          1.4         0.2     setosa           50
51           7.0         3.2          4.7         1.4 versicolor            1
52           6.4         3.2          4.5         1.5 versicolor            2
53           6.9         3.1          4.9         1.5 versicolor            3
..           ...         ...          ...         ...     ......           ..
98           6.2         2.9          4.3         1.3 versicolor           48
99           5.1         2.5          3.0         1.1 versicolor           49
100          5.7         2.8          4.1         1.3 versicolor           50
101          6.3         3.3          6.0         2.5  virginica            1
102          5.8         2.7          5.1         1.9  virginica            2
103          7.1         3.0          5.9         2.1  virginica            3
..           ...         ...          ...         ...     ......           ..
148          6.5         3.0          5.2         2.0  virginica           48
149          6.2         3.4          5.4         2.3  virginica           49
150          5.9         3.0          5.1         1.8  virginica           50