如何使用R索引主题 [英] How to Index subjects using R
本文介绍了如何使用R索引主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在R工作,我有一个数据集,每个主题有多个条目。我想创建一个索引变量,按主题索引。例如:
I am working in R and I have a Data set that has multiple entries for each subject. I want to create an index variable that indexes by subject. For example:
Subject Index
1 A 1
2 A 2
3 B 1
4 C 1
5 C 2
6 C 3
7 D 1
8 D 2
9 E 1
第一个A条目索引为1,而第二个A条目索引为2.第一个B条目索引为1,等等。
The first A entry is indexed as 1, while the second A entry is indexed as 2. The first B entry is indexed as 1, etc.
任何帮助都会非常棒!
推荐答案
Here.sa快速 data.table
aproach
Here.s a quick data.table
aproach
library(data.table)
setDT(df)[, Index := seq_len(.N), by = Subject][]
# Subject Index
# 1: A 1
# 2: A 2
# 3: B 1
# 4: C 1
# 5: C 2
# 6: C 3
# 7: D 1
# 8: D 2
# 9: E 1
或者基数R
with(df, ave(as.numeric(Subject), Subject, FUN = seq_along))
## [1] 1 2 1 1 2 3 1 2 1
或者使用 dplyr
(不要在 data.table
类上运行)
Or with dplyr
(don't run this on a data.table
class)
library(dplyr)
df %>%
group_by(Subject) %>%
mutate(Index = row_number())
这篇关于如何使用R索引主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文