如何使用 R 索引主题
How to Index subjects using R
我在 R 中工作,我有一个数据集,每个主题都有多个条目。我想创建一个按主题索引的索引变量。例如:
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,依此类推。
任何帮助都将是极好的!
Here.s 快速 data.table
方法
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
class 上)
library(dplyr)
df %>%
group_by(Subject) %>%
mutate(Index = row_number())
使用dplyr
library(dplyr)
df %>% group_by(Subject) %>% mutate(Index = 1:n())
你得到:
#Source: local data frame [9 x 2]
#Groups: 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 中工作,我有一个数据集,每个主题都有多个条目。我想创建一个按主题索引的索引变量。例如:
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,依此类推。
任何帮助都将是极好的!
Here.s 快速 data.table
方法
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
class 上)
library(dplyr)
df %>%
group_by(Subject) %>%
mutate(Index = row_number())
使用dplyr
library(dplyr)
df %>% group_by(Subject) %>% mutate(Index = 1:n())
你得到:
#Source: local data frame [9 x 2]
#Groups: 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