我正在尝试按R中的组或ID进行迭代,我无法弄清楚如何以简单的方式进行操作。
作为一个例子,我无法弄清楚如何在数据框中执行Study_Time
列。
ID Gender
1 Male
1 Male
1 Male
2 Female
2 Female
2 Female
3 Male
3 Male
3 Male
我需要得到这个:
ID Gender Study_Time
1 Male 1
1 Male 2
1 Male 3
2 Female 1
2 Female 2
2 Female 3
3 Male 1
3 Male 2
3 Male 3
PS:我尝试过if else条件,但实际数据来自一项超过50个学习时间的调查。所以我需要更简单的东西。
答案 0 :(得分:0)
您可以在不需要分组的情况下执行此操作:
df$Study_Time <- unlist(mapply(function(i) seq_len(i), rle(as.numeric(df$Gender))$lengths))
# ID Gender Study_Time
#1 1 Male 1
#2 1 Male 2
#3 1 Male 3
#4 2 Female 1
#5 2 Female 2
#6 2 Female 3
#7 3 Male 1
#8 3 Male 2
#9 3 Male 3
#10 3 Male 4
或者如果您想通过以下方式进行分组:
df$Study_Time <- unlist(aggregate(Gender~ID, df, seq_along)$Gender)
答案 1 :(得分:0)
您可以使用dplyr
:
library(dplyr)
df %>% group_by(id) %>% mutate(Study_Time = row_number())
答案 2 :(得分:0)
我们可以使用ave
base R
df1$Study_Time <- with(df1, ave(ID, ID, Gender, FUN = seq_along))
或data.table
library(data.table)
setDT(df1)[, Study_Time := 1:.N, .(ID, Gender)]