r - How to select first empty cell in a column? -


let's have dataframe

df1:      y1    y2     y3 1   1-5  6-10  11-15    #age-groups 2    3    2      2      #number of people per age-group  df2: id  age-group             1    na  2    na  3    na  4    na  5    na  6    na  7    na 

and want add data df1 in age-group column of df2:

df2: id  age-group  1    1-5  2    1-5  3    1-5  4    6-10  5    6-10  6    11-15  7    11-15 

so far have loop:

for (i in 1:3)    #number of columns in df1 {number=df1[2,i]  #stores number of times age-group 1-5 repeated (3) df2[1:number,2]=df1[1,i] #attach 1-5 label first 3 cells 

this loop work apply first age-group 1-5, when move next label, 6-10... how fill 2 empty cells starting @ row 4? of right now, loop start @ row 1. dataframe larger that, why loop better.

first assume df1's columns not factors. neat way enforce use:

    df1[] <- lapply(df1, as.character) 

you can use function rep(). it's important note rep() accepts vectors input both it's first , second arguments, loop unnecessary here. instead:

    df2[, 1] <- unlist(rep(df1[1, ], df1[2, ])) 

here, telling rep() repeat first age group "1-5" 3 times, "6-10" 2 times, etc. output of rep() list, unlist() can used convert list vector.


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -