Meesha Meesha - 1 year ago 82
R Question

Numbering in R based on a column value

Name Grade
John C
John C+
John C
John B
John A
John A+
Kat B
Kat C
Kat B

I want to add a new column,
, starting from 3 and then continue with its multiples. The rows are all sorted. The output would look something like

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


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

Can I do it without a loop?

Answer Source

Try this

df1 %>% group_by(Name) %>% mutate(Months=3*seq(n()))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download