Home > Back-end >  Repeated addition of dataframe columns with purrr
Repeated addition of dataframe columns with purrr

Time:07-29

I have this dataframe:

test_df <- data.frame(a=c(1:2),b=c(3:4),d=c(5:6))

What I want to do is generate a new dataframe with 2 columns where v1 = a b and v2 = a d, so that the dataframe looks like:

v1 v2
4 6
6 8

I can do this with manually, but what's the purrry way to do it?

CodePudding user response:

Using base R:

test_df[, 1 ]   test_df[, 2:3 ]
#   b d
# 1 4 6
# 2 6 8

CodePudding user response:

In base R simply,

sapply(test_df[-1], function(i)i   test_df$a)

     b d
[1,] 4 6
[2,] 6 8

CodePudding user response:

A possible solution, using dplyr:

library(dplyr)

test_df %>%
  transmute(across(b:d, ~ test_df$a   .x, .names="v{.col}"))

#>   vb vd
#> 1  4  6
#> 2  6  8

Using purrr::imap_dfc:

library(tidyverse)

imap_dfc(test_df[-1], ~ data.frame(test_df$a   .x) %>% 
  set_names(str_c("v", .y, collapse = "")))

#>   vb vd
#> 1  4  6
#> 2  6  8
  • Related