问题描述
我想从mtcars数据集中获取一列"mpg",并将其每个值除以1到100之间的数字.这将创建100个新列(每个除数为一列).列的名称应为"mpg_div_by_1","mpg_div_by_2","mpg_div_by_3".我想我在某处读到dplyr 1.0可以直接实现它,所以我不必编写循环.
I would like to take a column "mpg" from the mtcars dataset and divide each value of it by numbers from 1 to 100. This would create 100 new columns (one column per devisor). The names of the columns should be "mpg_div_by_1", "mpg_div_by_2", "mpg_div_by_3". I think I read somewhere that dplyr 1.0 could do it in a straightforward way so I dont have to write a loop.
推荐答案
我们可以在此处使用 map
变体.
We could use map
variants here.
library(purrr)
library(dplyr)
cols <- 1:5
map_dfc(cols, ~mtcars %>% transmute(!!paste0("mpg_div_by_", .x) := mpg / .x))
# mpg_div_by_1 mpg_div_by_2 mpg_div_by_3 mpg_div_by_4 mpg_div_by_5
#1 21.0 10.50 7.000000 5.250 4.20
#2 21.0 10.50 7.000000 5.250 4.20
#3 22.8 11.40 7.600000 5.700 4.56
#4 21.4 10.70 7.133333 5.350 4.28
#5 18.7 9.35 6.233333 4.675 3.74
#....
要将其添加到原始数据帧中,我们可以使用 bind_cols
:
To add it to original dataframes we can use bind_cols
:
map_dfc(cols, ~mtcars %>% transmute(!!paste0("mpg_div_by_", .x) := mpg / .x)) %>%
bind_cols(mtcars, .)
这在基数R中要简单得多:
This is much simpler in base R :
mtcars[paste0("mpg_div_by_", cols)] <- lapply(cols, function(x) mtcars$mpg / x)
这篇关于如何使用dplyr中的mutate创建一系列由向量指定和调用的列,这些列指定了突变值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!