使用dplyr一次生成多个列 [英] Generating multiple columns at once with dplyr

查看:65
本文介绍了使用dplyr一次生成多个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常不得不根据现有列中的值动态生成多个列。是否有以下等价的 dplyr

I often have to dynamically generate multiple columns based on values in existing columns. Is there a dplyr equivalent of the following?:

cols <- c("x", "y")
foo <- c("a", "b")
df <- data.frame(a = 1, b = 2)
df[cols] <- df[foo] * 5

> df
  a b x  y
1 1 2 5 10


推荐答案

不是最优雅的:

library(tidyverse)
df %>% 
  mutate_at(vars(foo),function(x) x*5) %>% 
   set_names(.,nm=cols) %>% 
   cbind(df,.)
  a b x  y
1 1 2 5 10

如@akrun所建议的,这可以使其更加优雅:

This can be made more elegant as suggested by @akrun :

df %>%
 mutate_at(vars(foo), list(new = ~ . * 5)) %>% 
 rename_at(vars(matches('new')), ~ c('x', 'y'))

这篇关于使用dplyr一次生成多个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆