Creating a mean variable, from variable names and weights supplied by vectors












1















Suppose I want to create a mean variable in a given dataframe based on two vectors, one specifying the names of the variables to use, and one specifying weights by which these variables should go into the mean variable:



vars <- c("a", "b", "c","d"))
weights <- c(0.5, 0.7, 0.8, 0.2))
df <- data.frame(cbind(c(1,4,5,7), c(2,3,7,5), c(1,1,2,3),
c(4,5,3,3), c(3,2,2,1), c(5,5,7,1)))
colnames(df) <- c("a","b","c","d","e","f")


How could I use dplyr::mutate() to create a mean variable that uses vars and weights to calculate a rowwise score? mutate() should specifically use the variables supplied by vars
The result should basically do the following:



df <- df %>% 
rowwise() %>%
mutate(comp = mean(c(vars[1]*weights[1], vars[2]*weights[2], ...)))


Written out:



df2 <- df %>% 
rowwise() %>%
mutate(comp = mean(c(0.5*a, 0.7*b, 0.8*c, 0.2*d)))


I can't figure out how to do this because, although vars contains the exact variable names that I want to use for mutate in my df, inside vars they are strings. How could I make mutate() understand that the strings vars contains relate to columns in my df? If you know another procedure not using mutate() that's fine also. Thanks!










share|improve this question





























    1















    Suppose I want to create a mean variable in a given dataframe based on two vectors, one specifying the names of the variables to use, and one specifying weights by which these variables should go into the mean variable:



    vars <- c("a", "b", "c","d"))
    weights <- c(0.5, 0.7, 0.8, 0.2))
    df <- data.frame(cbind(c(1,4,5,7), c(2,3,7,5), c(1,1,2,3),
    c(4,5,3,3), c(3,2,2,1), c(5,5,7,1)))
    colnames(df) <- c("a","b","c","d","e","f")


    How could I use dplyr::mutate() to create a mean variable that uses vars and weights to calculate a rowwise score? mutate() should specifically use the variables supplied by vars
    The result should basically do the following:



    df <- df %>% 
    rowwise() %>%
    mutate(comp = mean(c(vars[1]*weights[1], vars[2]*weights[2], ...)))


    Written out:



    df2 <- df %>% 
    rowwise() %>%
    mutate(comp = mean(c(0.5*a, 0.7*b, 0.8*c, 0.2*d)))


    I can't figure out how to do this because, although vars contains the exact variable names that I want to use for mutate in my df, inside vars they are strings. How could I make mutate() understand that the strings vars contains relate to columns in my df? If you know another procedure not using mutate() that's fine also. Thanks!










    share|improve this question



























      1












      1








      1








      Suppose I want to create a mean variable in a given dataframe based on two vectors, one specifying the names of the variables to use, and one specifying weights by which these variables should go into the mean variable:



      vars <- c("a", "b", "c","d"))
      weights <- c(0.5, 0.7, 0.8, 0.2))
      df <- data.frame(cbind(c(1,4,5,7), c(2,3,7,5), c(1,1,2,3),
      c(4,5,3,3), c(3,2,2,1), c(5,5,7,1)))
      colnames(df) <- c("a","b","c","d","e","f")


      How could I use dplyr::mutate() to create a mean variable that uses vars and weights to calculate a rowwise score? mutate() should specifically use the variables supplied by vars
      The result should basically do the following:



      df <- df %>% 
      rowwise() %>%
      mutate(comp = mean(c(vars[1]*weights[1], vars[2]*weights[2], ...)))


      Written out:



      df2 <- df %>% 
      rowwise() %>%
      mutate(comp = mean(c(0.5*a, 0.7*b, 0.8*c, 0.2*d)))


      I can't figure out how to do this because, although vars contains the exact variable names that I want to use for mutate in my df, inside vars they are strings. How could I make mutate() understand that the strings vars contains relate to columns in my df? If you know another procedure not using mutate() that's fine also. Thanks!










      share|improve this question
















      Suppose I want to create a mean variable in a given dataframe based on two vectors, one specifying the names of the variables to use, and one specifying weights by which these variables should go into the mean variable:



      vars <- c("a", "b", "c","d"))
      weights <- c(0.5, 0.7, 0.8, 0.2))
      df <- data.frame(cbind(c(1,4,5,7), c(2,3,7,5), c(1,1,2,3),
      c(4,5,3,3), c(3,2,2,1), c(5,5,7,1)))
      colnames(df) <- c("a","b","c","d","e","f")


      How could I use dplyr::mutate() to create a mean variable that uses vars and weights to calculate a rowwise score? mutate() should specifically use the variables supplied by vars
      The result should basically do the following:



      df <- df %>% 
      rowwise() %>%
      mutate(comp = mean(c(vars[1]*weights[1], vars[2]*weights[2], ...)))


      Written out:



      df2 <- df %>% 
      rowwise() %>%
      mutate(comp = mean(c(0.5*a, 0.7*b, 0.8*c, 0.2*d)))


      I can't figure out how to do this because, although vars contains the exact variable names that I want to use for mutate in my df, inside vars they are strings. How could I make mutate() understand that the strings vars contains relate to columns in my df? If you know another procedure not using mutate() that's fine also. Thanks!







      r vector mean mutate weighted






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 26 '18 at 10:46







      nklsstll

















      asked Nov 24 '18 at 16:28









      nklsstllnklsstll

      105




      105
























          3 Answers
          3






          active

          oldest

          votes


















          1














          You may use



          df %>% mutate(wmean = apply(.[vars], 1, weighted.mean, weights))
          # a b c d e f mean
          # 1 1 2 1 4 3 5 1.590909
          # 2 4 3 1 5 2 5 2.681818
          # 3 5 7 2 3 2 7 4.363636
          # 4 7 5 3 3 1 1 4.545455


          but there is not much to gain with tidyverse as base R approaches can be almost the same and end up being shorter:



          df$wmean <- apply(df[vars], 1, weighted.mean, weights)


          or one of the following:



          df$wmean <- colSums(t(df[vars]) * weights) / sum(weights)
          df$wmean <- as.matrix(df[vars]) %*% weights / sum(weights)
          df$wmean <- rowSums(sweep(df[vars], 2, weights, `*`)) / sum(weights)





          share|improve this answer

































            0














            Row-wise operations can be a bit tricky in the tidyverse. This is a case where some base R knowledge can be really handy. For example, you can do it in one line with apply (note that I corrected a typo in the line that creates weights and drop columns e and f, which do not have weights):



            vars <- c("a", "b", "c","d")
            weights <- c(0.5, 0.7, 0.8, 0.2)
            df <- data.frame(cbind(c(1,4,5,7), c(2,3,7,5), c(1,1,2,3),
            c(4,5,3,3), c(3,2,2,1), c(5,5,7,1)))
            colnames(df) <- c("a","b","c","d","e","f")

            df$weighted.mean <- apply(df %>% select(-e, -f), 1, weighted.mean, weights)

            a b c d e f weighted.mean
            1 1 2 1 4 3 5 1.590909
            2 4 3 1 5 2 5 2.681818
            3 5 7 2 3 2 7 4.363636
            4 7 5 3 3 1 1 4.545455


            If you really wanted to do it in the tidyverse, this should get you started:



            library(tidyverse)

            df.weights <- data.frame(vars, weights)

            df.new <- df %>%
            mutate(row.num = 1:n()) %>%
            gather(variable, value, -row.num) %>%
            left_join(df.weights, by = c(variable = 'vars')) %>%
            filter(variable %in% vars) %>%
            group_by(row.num) %>%
            mutate(weighted.mean = weighted.mean(value, weights))





            share|improve this answer


























            • Repeating the OP's as.vector call to surround a c encourages wasteful operations. That code looks pretty convoluted.

              – 42-
              Nov 24 '18 at 16:48













            • Didn't catch that, thank you.

              – jdobres
              Nov 24 '18 at 16:51











            • His code has a spelling error in the second (unnecessary) as.vectors.

              – 42-
              Nov 24 '18 at 16:53











            • Thank you, this also works but I ended up choosing Julius Vainoras answer because it uses the vars vector and is even shorter. Better catch up on some of that basic R knowledge!

              – nklsstll
              Nov 24 '18 at 17:23



















            0














            There should be a tidyverse solution using pmap, but it eludes me. Here's another approach using tidyverse packages purrr and tibble





            library(tidyverse)

            vars <- c("a", "b", "c", "d")
            weights <- c(0.5, 0.7, 0.8, 0.2)
            df <- data.frame(cbind(c(1,4,5,7), c(2,3,7,5), c(1,1,2,3),
            c(4,5,3,3), c(3,2,2,1), c(5,5,7,1)))
            colnames(df) <- c("a","b","c","d","e","f")

            df %>%
            transpose() %>%
            simplify_all() %>%
            map_dbl(~weighted.mean(.x[vars], weights)) %>%
            add_column(df, wmean = .)
            #> a b c d e f wmean
            #> 1 1 2 1 4 3 5 1.590909
            #> 2 4 3 1 5 2 5 2.681818
            #> 3 5 7 2 3 2 7 4.363636
            #> 4 7 5 3 3 1 1 4.545455


            Created on 2018-11-24 by the reprex package (v0.2.1)






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53460150%2fcreating-a-mean-variable-from-variable-names-and-weights-supplied-by-vectors%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1














              You may use



              df %>% mutate(wmean = apply(.[vars], 1, weighted.mean, weights))
              # a b c d e f mean
              # 1 1 2 1 4 3 5 1.590909
              # 2 4 3 1 5 2 5 2.681818
              # 3 5 7 2 3 2 7 4.363636
              # 4 7 5 3 3 1 1 4.545455


              but there is not much to gain with tidyverse as base R approaches can be almost the same and end up being shorter:



              df$wmean <- apply(df[vars], 1, weighted.mean, weights)


              or one of the following:



              df$wmean <- colSums(t(df[vars]) * weights) / sum(weights)
              df$wmean <- as.matrix(df[vars]) %*% weights / sum(weights)
              df$wmean <- rowSums(sweep(df[vars], 2, weights, `*`)) / sum(weights)





              share|improve this answer






























                1














                You may use



                df %>% mutate(wmean = apply(.[vars], 1, weighted.mean, weights))
                # a b c d e f mean
                # 1 1 2 1 4 3 5 1.590909
                # 2 4 3 1 5 2 5 2.681818
                # 3 5 7 2 3 2 7 4.363636
                # 4 7 5 3 3 1 1 4.545455


                but there is not much to gain with tidyverse as base R approaches can be almost the same and end up being shorter:



                df$wmean <- apply(df[vars], 1, weighted.mean, weights)


                or one of the following:



                df$wmean <- colSums(t(df[vars]) * weights) / sum(weights)
                df$wmean <- as.matrix(df[vars]) %*% weights / sum(weights)
                df$wmean <- rowSums(sweep(df[vars], 2, weights, `*`)) / sum(weights)





                share|improve this answer




























                  1












                  1








                  1







                  You may use



                  df %>% mutate(wmean = apply(.[vars], 1, weighted.mean, weights))
                  # a b c d e f mean
                  # 1 1 2 1 4 3 5 1.590909
                  # 2 4 3 1 5 2 5 2.681818
                  # 3 5 7 2 3 2 7 4.363636
                  # 4 7 5 3 3 1 1 4.545455


                  but there is not much to gain with tidyverse as base R approaches can be almost the same and end up being shorter:



                  df$wmean <- apply(df[vars], 1, weighted.mean, weights)


                  or one of the following:



                  df$wmean <- colSums(t(df[vars]) * weights) / sum(weights)
                  df$wmean <- as.matrix(df[vars]) %*% weights / sum(weights)
                  df$wmean <- rowSums(sweep(df[vars], 2, weights, `*`)) / sum(weights)





                  share|improve this answer















                  You may use



                  df %>% mutate(wmean = apply(.[vars], 1, weighted.mean, weights))
                  # a b c d e f mean
                  # 1 1 2 1 4 3 5 1.590909
                  # 2 4 3 1 5 2 5 2.681818
                  # 3 5 7 2 3 2 7 4.363636
                  # 4 7 5 3 3 1 1 4.545455


                  but there is not much to gain with tidyverse as base R approaches can be almost the same and end up being shorter:



                  df$wmean <- apply(df[vars], 1, weighted.mean, weights)


                  or one of the following:



                  df$wmean <- colSums(t(df[vars]) * weights) / sum(weights)
                  df$wmean <- as.matrix(df[vars]) %*% weights / sum(weights)
                  df$wmean <- rowSums(sweep(df[vars], 2, weights, `*`)) / sum(weights)






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 24 '18 at 16:54

























                  answered Nov 24 '18 at 16:49









                  Julius VainoraJulius Vainora

                  37.8k76584




                  37.8k76584

























                      0














                      Row-wise operations can be a bit tricky in the tidyverse. This is a case where some base R knowledge can be really handy. For example, you can do it in one line with apply (note that I corrected a typo in the line that creates weights and drop columns e and f, which do not have weights):



                      vars <- c("a", "b", "c","d")
                      weights <- c(0.5, 0.7, 0.8, 0.2)
                      df <- data.frame(cbind(c(1,4,5,7), c(2,3,7,5), c(1,1,2,3),
                      c(4,5,3,3), c(3,2,2,1), c(5,5,7,1)))
                      colnames(df) <- c("a","b","c","d","e","f")

                      df$weighted.mean <- apply(df %>% select(-e, -f), 1, weighted.mean, weights)

                      a b c d e f weighted.mean
                      1 1 2 1 4 3 5 1.590909
                      2 4 3 1 5 2 5 2.681818
                      3 5 7 2 3 2 7 4.363636
                      4 7 5 3 3 1 1 4.545455


                      If you really wanted to do it in the tidyverse, this should get you started:



                      library(tidyverse)

                      df.weights <- data.frame(vars, weights)

                      df.new <- df %>%
                      mutate(row.num = 1:n()) %>%
                      gather(variable, value, -row.num) %>%
                      left_join(df.weights, by = c(variable = 'vars')) %>%
                      filter(variable %in% vars) %>%
                      group_by(row.num) %>%
                      mutate(weighted.mean = weighted.mean(value, weights))





                      share|improve this answer


























                      • Repeating the OP's as.vector call to surround a c encourages wasteful operations. That code looks pretty convoluted.

                        – 42-
                        Nov 24 '18 at 16:48













                      • Didn't catch that, thank you.

                        – jdobres
                        Nov 24 '18 at 16:51











                      • His code has a spelling error in the second (unnecessary) as.vectors.

                        – 42-
                        Nov 24 '18 at 16:53











                      • Thank you, this also works but I ended up choosing Julius Vainoras answer because it uses the vars vector and is even shorter. Better catch up on some of that basic R knowledge!

                        – nklsstll
                        Nov 24 '18 at 17:23
















                      0














                      Row-wise operations can be a bit tricky in the tidyverse. This is a case where some base R knowledge can be really handy. For example, you can do it in one line with apply (note that I corrected a typo in the line that creates weights and drop columns e and f, which do not have weights):



                      vars <- c("a", "b", "c","d")
                      weights <- c(0.5, 0.7, 0.8, 0.2)
                      df <- data.frame(cbind(c(1,4,5,7), c(2,3,7,5), c(1,1,2,3),
                      c(4,5,3,3), c(3,2,2,1), c(5,5,7,1)))
                      colnames(df) <- c("a","b","c","d","e","f")

                      df$weighted.mean <- apply(df %>% select(-e, -f), 1, weighted.mean, weights)

                      a b c d e f weighted.mean
                      1 1 2 1 4 3 5 1.590909
                      2 4 3 1 5 2 5 2.681818
                      3 5 7 2 3 2 7 4.363636
                      4 7 5 3 3 1 1 4.545455


                      If you really wanted to do it in the tidyverse, this should get you started:



                      library(tidyverse)

                      df.weights <- data.frame(vars, weights)

                      df.new <- df %>%
                      mutate(row.num = 1:n()) %>%
                      gather(variable, value, -row.num) %>%
                      left_join(df.weights, by = c(variable = 'vars')) %>%
                      filter(variable %in% vars) %>%
                      group_by(row.num) %>%
                      mutate(weighted.mean = weighted.mean(value, weights))





                      share|improve this answer


























                      • Repeating the OP's as.vector call to surround a c encourages wasteful operations. That code looks pretty convoluted.

                        – 42-
                        Nov 24 '18 at 16:48













                      • Didn't catch that, thank you.

                        – jdobres
                        Nov 24 '18 at 16:51











                      • His code has a spelling error in the second (unnecessary) as.vectors.

                        – 42-
                        Nov 24 '18 at 16:53











                      • Thank you, this also works but I ended up choosing Julius Vainoras answer because it uses the vars vector and is even shorter. Better catch up on some of that basic R knowledge!

                        – nklsstll
                        Nov 24 '18 at 17:23














                      0












                      0








                      0







                      Row-wise operations can be a bit tricky in the tidyverse. This is a case where some base R knowledge can be really handy. For example, you can do it in one line with apply (note that I corrected a typo in the line that creates weights and drop columns e and f, which do not have weights):



                      vars <- c("a", "b", "c","d")
                      weights <- c(0.5, 0.7, 0.8, 0.2)
                      df <- data.frame(cbind(c(1,4,5,7), c(2,3,7,5), c(1,1,2,3),
                      c(4,5,3,3), c(3,2,2,1), c(5,5,7,1)))
                      colnames(df) <- c("a","b","c","d","e","f")

                      df$weighted.mean <- apply(df %>% select(-e, -f), 1, weighted.mean, weights)

                      a b c d e f weighted.mean
                      1 1 2 1 4 3 5 1.590909
                      2 4 3 1 5 2 5 2.681818
                      3 5 7 2 3 2 7 4.363636
                      4 7 5 3 3 1 1 4.545455


                      If you really wanted to do it in the tidyverse, this should get you started:



                      library(tidyverse)

                      df.weights <- data.frame(vars, weights)

                      df.new <- df %>%
                      mutate(row.num = 1:n()) %>%
                      gather(variable, value, -row.num) %>%
                      left_join(df.weights, by = c(variable = 'vars')) %>%
                      filter(variable %in% vars) %>%
                      group_by(row.num) %>%
                      mutate(weighted.mean = weighted.mean(value, weights))





                      share|improve this answer















                      Row-wise operations can be a bit tricky in the tidyverse. This is a case where some base R knowledge can be really handy. For example, you can do it in one line with apply (note that I corrected a typo in the line that creates weights and drop columns e and f, which do not have weights):



                      vars <- c("a", "b", "c","d")
                      weights <- c(0.5, 0.7, 0.8, 0.2)
                      df <- data.frame(cbind(c(1,4,5,7), c(2,3,7,5), c(1,1,2,3),
                      c(4,5,3,3), c(3,2,2,1), c(5,5,7,1)))
                      colnames(df) <- c("a","b","c","d","e","f")

                      df$weighted.mean <- apply(df %>% select(-e, -f), 1, weighted.mean, weights)

                      a b c d e f weighted.mean
                      1 1 2 1 4 3 5 1.590909
                      2 4 3 1 5 2 5 2.681818
                      3 5 7 2 3 2 7 4.363636
                      4 7 5 3 3 1 1 4.545455


                      If you really wanted to do it in the tidyverse, this should get you started:



                      library(tidyverse)

                      df.weights <- data.frame(vars, weights)

                      df.new <- df %>%
                      mutate(row.num = 1:n()) %>%
                      gather(variable, value, -row.num) %>%
                      left_join(df.weights, by = c(variable = 'vars')) %>%
                      filter(variable %in% vars) %>%
                      group_by(row.num) %>%
                      mutate(weighted.mean = weighted.mean(value, weights))






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 24 '18 at 16:55

























                      answered Nov 24 '18 at 16:44









                      jdobresjdobres

                      4,8861522




                      4,8861522













                      • Repeating the OP's as.vector call to surround a c encourages wasteful operations. That code looks pretty convoluted.

                        – 42-
                        Nov 24 '18 at 16:48













                      • Didn't catch that, thank you.

                        – jdobres
                        Nov 24 '18 at 16:51











                      • His code has a spelling error in the second (unnecessary) as.vectors.

                        – 42-
                        Nov 24 '18 at 16:53











                      • Thank you, this also works but I ended up choosing Julius Vainoras answer because it uses the vars vector and is even shorter. Better catch up on some of that basic R knowledge!

                        – nklsstll
                        Nov 24 '18 at 17:23



















                      • Repeating the OP's as.vector call to surround a c encourages wasteful operations. That code looks pretty convoluted.

                        – 42-
                        Nov 24 '18 at 16:48













                      • Didn't catch that, thank you.

                        – jdobres
                        Nov 24 '18 at 16:51











                      • His code has a spelling error in the second (unnecessary) as.vectors.

                        – 42-
                        Nov 24 '18 at 16:53











                      • Thank you, this also works but I ended up choosing Julius Vainoras answer because it uses the vars vector and is even shorter. Better catch up on some of that basic R knowledge!

                        – nklsstll
                        Nov 24 '18 at 17:23

















                      Repeating the OP's as.vector call to surround a c encourages wasteful operations. That code looks pretty convoluted.

                      – 42-
                      Nov 24 '18 at 16:48







                      Repeating the OP's as.vector call to surround a c encourages wasteful operations. That code looks pretty convoluted.

                      – 42-
                      Nov 24 '18 at 16:48















                      Didn't catch that, thank you.

                      – jdobres
                      Nov 24 '18 at 16:51





                      Didn't catch that, thank you.

                      – jdobres
                      Nov 24 '18 at 16:51













                      His code has a spelling error in the second (unnecessary) as.vectors.

                      – 42-
                      Nov 24 '18 at 16:53





                      His code has a spelling error in the second (unnecessary) as.vectors.

                      – 42-
                      Nov 24 '18 at 16:53













                      Thank you, this also works but I ended up choosing Julius Vainoras answer because it uses the vars vector and is even shorter. Better catch up on some of that basic R knowledge!

                      – nklsstll
                      Nov 24 '18 at 17:23





                      Thank you, this also works but I ended up choosing Julius Vainoras answer because it uses the vars vector and is even shorter. Better catch up on some of that basic R knowledge!

                      – nklsstll
                      Nov 24 '18 at 17:23











                      0














                      There should be a tidyverse solution using pmap, but it eludes me. Here's another approach using tidyverse packages purrr and tibble





                      library(tidyverse)

                      vars <- c("a", "b", "c", "d")
                      weights <- c(0.5, 0.7, 0.8, 0.2)
                      df <- data.frame(cbind(c(1,4,5,7), c(2,3,7,5), c(1,1,2,3),
                      c(4,5,3,3), c(3,2,2,1), c(5,5,7,1)))
                      colnames(df) <- c("a","b","c","d","e","f")

                      df %>%
                      transpose() %>%
                      simplify_all() %>%
                      map_dbl(~weighted.mean(.x[vars], weights)) %>%
                      add_column(df, wmean = .)
                      #> a b c d e f wmean
                      #> 1 1 2 1 4 3 5 1.590909
                      #> 2 4 3 1 5 2 5 2.681818
                      #> 3 5 7 2 3 2 7 4.363636
                      #> 4 7 5 3 3 1 1 4.545455


                      Created on 2018-11-24 by the reprex package (v0.2.1)






                      share|improve this answer




























                        0














                        There should be a tidyverse solution using pmap, but it eludes me. Here's another approach using tidyverse packages purrr and tibble





                        library(tidyverse)

                        vars <- c("a", "b", "c", "d")
                        weights <- c(0.5, 0.7, 0.8, 0.2)
                        df <- data.frame(cbind(c(1,4,5,7), c(2,3,7,5), c(1,1,2,3),
                        c(4,5,3,3), c(3,2,2,1), c(5,5,7,1)))
                        colnames(df) <- c("a","b","c","d","e","f")

                        df %>%
                        transpose() %>%
                        simplify_all() %>%
                        map_dbl(~weighted.mean(.x[vars], weights)) %>%
                        add_column(df, wmean = .)
                        #> a b c d e f wmean
                        #> 1 1 2 1 4 3 5 1.590909
                        #> 2 4 3 1 5 2 5 2.681818
                        #> 3 5 7 2 3 2 7 4.363636
                        #> 4 7 5 3 3 1 1 4.545455


                        Created on 2018-11-24 by the reprex package (v0.2.1)






                        share|improve this answer


























                          0












                          0








                          0







                          There should be a tidyverse solution using pmap, but it eludes me. Here's another approach using tidyverse packages purrr and tibble





                          library(tidyverse)

                          vars <- c("a", "b", "c", "d")
                          weights <- c(0.5, 0.7, 0.8, 0.2)
                          df <- data.frame(cbind(c(1,4,5,7), c(2,3,7,5), c(1,1,2,3),
                          c(4,5,3,3), c(3,2,2,1), c(5,5,7,1)))
                          colnames(df) <- c("a","b","c","d","e","f")

                          df %>%
                          transpose() %>%
                          simplify_all() %>%
                          map_dbl(~weighted.mean(.x[vars], weights)) %>%
                          add_column(df, wmean = .)
                          #> a b c d e f wmean
                          #> 1 1 2 1 4 3 5 1.590909
                          #> 2 4 3 1 5 2 5 2.681818
                          #> 3 5 7 2 3 2 7 4.363636
                          #> 4 7 5 3 3 1 1 4.545455


                          Created on 2018-11-24 by the reprex package (v0.2.1)






                          share|improve this answer













                          There should be a tidyverse solution using pmap, but it eludes me. Here's another approach using tidyverse packages purrr and tibble





                          library(tidyverse)

                          vars <- c("a", "b", "c", "d")
                          weights <- c(0.5, 0.7, 0.8, 0.2)
                          df <- data.frame(cbind(c(1,4,5,7), c(2,3,7,5), c(1,1,2,3),
                          c(4,5,3,3), c(3,2,2,1), c(5,5,7,1)))
                          colnames(df) <- c("a","b","c","d","e","f")

                          df %>%
                          transpose() %>%
                          simplify_all() %>%
                          map_dbl(~weighted.mean(.x[vars], weights)) %>%
                          add_column(df, wmean = .)
                          #> a b c d e f wmean
                          #> 1 1 2 1 4 3 5 1.590909
                          #> 2 4 3 1 5 2 5 2.681818
                          #> 3 5 7 2 3 2 7 4.363636
                          #> 4 7 5 3 3 1 1 4.545455


                          Created on 2018-11-24 by the reprex package (v0.2.1)







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 25 '18 at 2:34









                          Jake KauppJake Kaupp

                          5,64721428




                          5,64721428






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53460150%2fcreating-a-mean-variable-from-variable-names-and-weights-supplied-by-vectors%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              404 Error Contact Form 7 ajax form submitting

                              How to know if a Active Directory user can login interactively

                              TypeError: fit_transform() missing 1 required positional argument: 'X'