Mutating multiple columns in a data frame using dplyr

后端 未结 4 2038
一个人的身影
一个人的身影 2020-12-09 05:24

I have the following data frame df:

  v1 v2 v3 v4
1  1  5  7  4
2  2  6 10  3

And I want to obtain the following data frame

4条回答
  •  半阙折子戏
    2020-12-09 05:57

    I think I found a solution:

    df %>%
      mutate(n = df[1:(ncol(df)/2)] * df[(1+ncol(df)/2):(ncol(df))]) %>% head()
    

    The result is valid for any number of variables. It only remains a problem with the name of the new variables. This is the result:

      v1 v2 v3 v4 n.v1 n.v2
    1  1  5  7  4    7   20
    2  2  6 10  3   20   18
    

提交回复
热议问题