Search code examples
rloopssapply

R Loop To Make New Vectors


data = data.frame("id"=c(1,2,3,4,5,6,7,8,9,10),
                  "group"=c(1,1,2,1,2,2,2,2,1,2),
                  "type"=c(1,1,2,3,2,2,3,3,3,1),
                  "score1"=c(sample(1:4,10,r=T)),
                  "score2"=c(sample(1:4,10,r=T)),
                  "score3"=c(sample(1:4,10,r=T)),
                  "score4"=c(sample(1:4,10,r=T)),
                  "score5"=c(sample(1:4,10,r=T)),
                  "weight1"=c(173,109,136,189,186,146,173,102,178,174),
                  "weight2"=c(147,187,125,126,120,165,142,129,144,197),
                  "weight3"=c(103,192,102,159,128,179,195,193,135,145),
                  "weight4"=c(114,182,199,101,111,116,198,123,119,181),
                  "weight5"=c(159,125,104,171,166,154,197,124,180,154))

That is a sample of my data. I want population-weighted counts of the score variable like so:

count(data, score1, wt = weight1)
count(data, score2, wt = weight2)
count(data, score3, wt = weight3)
count(data, score4, wt = weight4)
count(data, score5, wt = weight5)

However I aim to make a loop of a type such that, I can do this for every combination of 'group' and 'type' for scores1-5 and store these in separate vectors such that

vec1 = weighted score variable for scores1-5 for group = 1 and type = 1
vec2 = weighted score variable for scores1-5 for group = 1 and type = 2
vec3 = weighted score variable for scores1-5 for group = 1 and type = 3

and so on and so forth.


Solution

  • We can use map to loop through each of the corresponding 'score', 'weight' and get the count

    library(tidyverse)
    out <- map(1:5, ~ 
           data %>%
             select(group, type, matches(as.character(.x))) %>% 
             group_by(group, type) %>%
             count(!! rlang::sym(str_c("score", .x)), 
             wt = !! rlang::sym(str_c("weight", .x))))
    

    The output would be a list of frequency count tibble. If we want to create a single data, use map_df with .id