[英]Repeated addition of dataframe columns with purrr
I have this dataframe:我有这个 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:我想要做的是生成一个新的 dataframe 有 2 列,其中 v1 = a+b 和 v2 = a+d,因此 dataframe 看起来像:
v1 v1 | v2 v2 |
---|---|
4 4 | 6 6 |
6 6 | 8 8 |
I can do this with manually, but what's the purrry way to do it?我可以手动做到这一点,但有什么好方法呢?
Using base R:使用基础 R:
test_df[, 1 ] + test_df[, 2:3 ]
# b d
# 1 4 6
# 2 6 8
In base R simply,简单地在基础R,
sapply(test_df[-1], function(i)i + test_df$a)
b d
[1,] 4 6
[2,] 6 8
A possible solution, using dplyr
:一个可能的解决方案,使用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
:使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.