Name Grade
John C
John C+
John C
John B
John A
John A+
Kat B
Kat C
Kat B
我想添加一个新列Months
,从3开始,然后继续其倍数。行都是排序的。输出看起来像
Name Grade Months
John C 3
John C+ 6
John C 9
John B 12
John A 15
John A+ 18
Kat B 3
Kat C 6
Kat B 9
RCODE
name <- df$Name[1]
count <- 0
for (i in 1:length(df[,1])){
if (name!=df$Name[i]){
count <- 0
name <- df$Name[i]
}
df$Months[i] <- count
count <- count + 3
}
我可以在没有循环的情况下完成吗?
答案 0 :(得分:5)
试试这个
library(dplyr)
df1 %>% group_by(Name) %>% mutate(Months=3*seq(n()))
答案 1 :(得分:3)
您可以对按Name
分组的3向量执行累计求和:
with(df, ave(rep(3, length(Name)), Name, FUN = cumsum))
# [1] 3 6 9 12 15 18 3 6 9
答案 2 :(得分:1)
使用data.table
,将'data.frame'转换为'data.table'(setDT(df1)
),按'名称'分组,分配(:=
)3的乘积行数到'月'。
library(data.table)
setDT(df1)[, Months := 3* seq_len(.N) , by = Name]
df1
# Name Grade Months
#1: John C 3
#2: John C+ 6
#3: John C 9
#4: John B 12
#5: John A 15
#6: John A+ 18
#7: Kat B 3
#8: Kat C 6
#9: Kat B 9
答案 3 :(得分:1)
另一个替代方案,非常类似于Psidom的答案,使用seq
与ave
和1:nrow(df)
代替df$Name
来避免将字符向量作为输出。
ave(1:nrow(df), df$Name, FUN = seq)*3
# [1] 3 6 9 12 15 18 3 6 9