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