R循环制作新向量

时间:2019-05-31 13:55:57

标签: r loops sapply

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))

这是我的数据的一个示例。我想要分数变量的人口加权计数,如下所示:

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)

但是我的目标是创建一个类型的循环,这样我可以对得分1-5的“组”和“类型”的每种组合进行此操作,并将它们存储在单独的向量中,以使

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

以此类推。

2 个答案:

答案 0 :(得分:1)

我们可以使用map遍历每个相应的“得分”,“权重”并获得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))))

输出将是频率list count的{​​{1}}。如果我们要创建一个数据,请将tibblemap_df

一起使用

答案 1 :(得分:0)

我不确定确切了解您的预期输出是什么,但是您可能想尝试这样的事情:

for (i in 1:max(data[["group"]])) { #looping through groups
  weighted_score <- ... ## create your wheighted score for group i here

  name <- paste("vec",i,sep="")
  assign(name,weighted_score)

}