[英]mutating multiple columns automatically in a df
我想从列列表中自动生成数据框中的交互。 我有这个例子..
library(tidyverse)
library(nycflights13)
df<- nycflights13::weather
interactions <- c("hour","temp","dewp","humid","wind_dir","wind_speed")
df<- df %>% mutate (hour_temp= hour*temp, hour_dewp= hour*dewp)
现在我试图弄清楚如何自动生成所有列(例如继续使用 temp dewp、temp hum ...)
有任何想法吗?
我们可以使用combn
来获取“interactions”中的所有组合,一次取 2 个,在combn
指定FUN
以select
这些列, transmute
乘积 ( *
) 并将它们与原始数据集绑定
library(dplyr)
library(purrr)
library(stringr)
out <- combn(interactions, 2, function(x) df %>%
dplyr::select(x) %>%
transmute(!! str_c(x, collapse="_"):= reduce(., `*`)),
simplify = FALSE) %>%
bind_cols %>%
bind_cols(df, .)
- 检查输出
names(out)
#[1] "origin" "year" "month" "day" "hour"
#[6] "temp" "dewp" "humid" "wind_dir" "wind_speed"
#[11] "wind_gust" "precip" "pressure" "visib" "time_hour"
#[16] "hour_temp" "hour_dewp" "hour_humid" "hour_wind_dir" "hour_wind_speed"
#[21] "temp_dewp" "temp_humid" "temp_wind_dir" "temp_wind_speed" "dewp_humid"
#[26] "dewp_wind_dir" "dewp_wind_speed" "humid_wind_dir" "humid_wind_speed" "wind_dir_wind_speed"
或使用base R
m1 <- combn(interactions, 2)
df[paste(m1[1,], m1[2, ], sep="_")] <- lapply(asplit(m1, 2),
function(x) do.call(`*`, df[x]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.