Search code examples
rnested-loopslapply

Apply different functions to every nth row


I have a large dataframe:

age<- c(25,25,25,25,25,30,30,30,30,30)
pop<-c(1000,1000,1000,1000,1000,800,800,800,800,800)
df<-rbind(age,pop)

Actually I have in the same dataframe the iteration of this structure multiple times (for each sex and year). What I want to do is, to change the ageclasses to increasing numbers- beginning in every 5th. row. To have it like this:

age<- c(25,26,27,28,29,30,31,32,33,34)
pop<-c(1000,1000,1000,1000,1000,800,800,800,800,800)
df_new<-rbind(age,pop)

My thougths were about to apply age +0, age +1, age +2, age +3, age +4; to every multiple of 1st,2nd,3rd,4rd,5rd row. I tried nested loops or lapply but nothing worked for me.


Solution

  • I think your data should be structured in this format.

    age<- c(25,25,25,25,25,30,30,30,30,30)
    pop<-c(1000,1000,1000,1000,1000,800,800,800,800,800)
    df<-data.frame(age,pop)
    

    You can use seq function.

    library(dplyr)
    df %>% mutate(age = seq(min(age), length.out = n()))
    
    #   age  pop
    #1   25 1000
    #2   26 1000
    #3   27 1000
    #4   28 1000
    #5   29 1000
    #6   30  800
    #7   31  800
    #8   32  800
    #9   33  800
    #10  34  800
    

    If you want to do this for each sex and year variables you can add them in group_by :

    df %>% group_by(sex, year) %>% mutate(age = seq(min(age), length.out = n()))