Reproducible tibble: I have a database similar to the one shown below. The difference being that the database I'm working with is much bigger.
general_tibble <- tibble(gender = c("female", "female", "male"),
age = c(18, 19,18),
age_partner = c(22,20,17),
max_age = c(60, 60, 65),
nrs =c(42,41,47))
general_tibble results in :
gender age age_partner max_age nrs
1 female 18 22 60 42
2 female 19 20 60 41
3 male 18 17 65 47
Question:
How do I create a new table from a previous table, that takes the value of nrs, and creates a column variable, called n, that goes from 0 to the value in nrs?
To illustrate further, in row 1 of general_tibble the column nrs is equal to 42 so the column would go from 0 to 42, in row 2 nrsis equal to 41 so the column would go from 0 to 41, and the same for row 3.
I am currently using the code below. It works, but when general_tibble is too big, the code performs really slow.
general_list <- list()
for(i in 1:NROW(general_tibble)){
general_list[[i]] <- data.frame(general_tibble[i, ],
n = 0:general_tibble[[i, "nrs"]])
}
Then I bind_rows() general_list to obtain general_binded
general_binded <- bind_rows(general_list)
general_binded[c(1:5, 38:42),] results in :
gender age age_partner max_age nrs n
1 female 18 22 60 42 0
2 female 18 22 60 42 1
3 female 18 22 60 42 2
4 female 18 22 60 42 3
5 female 18 22 60 42 4
38 female 18 22 60 42 37
39 female 18 22 60 42 38
40 female 18 22 60 42 39
41 female 18 22 60 42 40
42 female 18 22 60 42 41
PS: In the for loop I use data.frame() instead of tibble() because i want to recycle the rows. If you have some sort of advice involving tibbles or dataframes, ill gladly take it.