简体   繁体   中英

Repeated addition of dataframe columns with purrr

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?

Using base R:

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

In base R simply,

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM