How to Index subjects using R [duplicate]

做~自己de王妃 提交于 2019-12-25 03:21:32

问题


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

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.

Any help would be excellent!


回答1:


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

Or with base R

with(df, ave(as.numeric(Subject), Subject, FUN = seq_along))
## [1] 1 2 1 1 2 3 1 2 1

Or with dplyr (don't run this on a data.table class)

library(dplyr)
df %>%
  group_by(Subject) %>%
  mutate(Index = row_number())



回答2:


Using dplyr

library(dplyr)
df %>% group_by(Subject) %>% mutate(Index = 1:n())

You get:

#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


来源:https://stackoverflow.com/questions/28841552/how-to-index-subjects-using-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!