R:为包含相同标签的行分配增量编号 [英] R: assign incremental numbers to rows containing a same label
本文介绍了R:为包含相同标签的行分配增量编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定数据框 df
如下:
chrom position strand value label
chr1 17432 - 0 romeo
chr1 17433 - 0 romeo
chr1 17434 - 0 romeo
chr1 17435 - 0 romeo
chr1 17409 - 1 juliet
chr1 17410 - 1 juliet
chr1 17411 - 1 juliet
我想对从1开始共享相同标签
的行进行编号,并将这些数字放在一个新列中。 (我不只是想计算他们,目标是数字)。输出应如下所示:
For each group of labels, I would like to number the lines that share the same label
starting from 1 and put those numbers in a new column. (I don't just want to count them, the goal is to number them). The output should look something like this:
chrom position strand value label number
chr1 17432 - 0 romeo 1
chr1 17433 - 0 romeo 2
chr1 17434 - 0 romeo 3
chr1 17435 - 0 romeo 4
chr1 17409 - 1 juliet 1
chr1 17410 - 1 juliet 2
chr1 17411 - 1 juliet 3
是否有一个函数或包执行作业? p>
Is there a function or package that does the job?
推荐答案
dat <- read.table(header = TRUE, text = "chrom position strand value label
chr1 17432 - 0 romeo
chr1 17433 - 0 romeo
chr1 17434 - 0 romeo
chr1 17435 - 0 romeo
chr1 17409 - 1 juliet
chr1 17410 - 1 juliet
chr1 17411 - 1 juliet")
#install.packages('dplyr')
library(dplyr)
dat %.%
group_by(label) %.%
mutate(number = 1:n())
Source: local data frame [7 x 6]
Groups: label
chrom position strand value label number
1 chr1 17432 - 0 romeo 1
2 chr1 17433 - 0 romeo 2
3 chr1 17434 - 0 romeo 3
4 chr1 17435 - 0 romeo 4
5 chr1 17409 - 1 juliet 1
6 chr1 17410 - 1 juliet 2
7 chr1 17411 - 1 juliet 3
我相信在R中有很多其他的可能性。Data.Table是一个(见下面的例子)。不确定为什么我需要添加print()来显示结果。
I am sure there are many other possibilities in R. Data.Table is one (see example below). Not sure why I needed to add print() to show the result however.
require(data.table)
dt <- data.table(dat)
print(dt[, number := 1:.N, by = label])
chrom position strand value label number
1: chr1 17432 - 0 romeo 1
2: chr1 17433 - 0 romeo 2
3: chr1 17434 - 0 romeo 3
4: chr1 17435 - 0 romeo 4
5: chr1 17409 - 1 juliet 1
6: chr1 17410 - 1 juliet 2
7: chr1 17411 - 1 juliet 3
这篇关于R:为包含相同标签的行分配增量编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文