Mutating multiple columns in a data frame using dplyr

后端 未结 4 2029
一个人的身影
一个人的身影 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:58

    We can use base R instead of using any extra packages like dplyr or data.table

    We can use mapply to vectorize the operation for multiple vectors at the same time

    n <- ncol(df)/2
    mapply(`*`, df[1:n], df[(n + 1):ncol(df)])
    
    #     v1 v2
    #[1,]  7 20
    #[2,] 20 18
    

    We can merge (cbind) this dataframe to your original one then.


    If you are interested in tidyverse solution the equivalent in purrr would be variants of map2

    purrr::map2_df(df[1:n], df[(n + 1):ncol(df)], `*`)
    
    # A tibble: 2 x 2
    #     v1    v2
    #   
    #1     7    20
    #2    20    18
    

提交回复
热议问题