r-使用purrr重复添加数据帧列



我有这个数据帧:

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

我想做的是生成一个新的数据帧,它有两列,其中v1=a+b,v2=a+d,这样数据帧看起来像:

v1v2
46
68

使用基R:

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

简单地说,在基R中,

sapply(test_df[-1], function(i)i + test_df$a)
b d
[1,] 4 6
[2,] 6 8

使用dplyr:的可能解决方案

library(dplyr)
test_df %>%
transmute(across(b:d, ~ test_df$a + .x, .names="v{.col}"))
#>   vb vd
#> 1  4  6
#> 2  6  8

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

最新更新