使用dplyr mutate基于列名称的向量创建新列 [英] use dplyr mutate to create new columns based on a vector of column names
本文介绍了使用dplyr mutate基于列名称的向量创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取某些列的日志,并创建全部都命名为log [原始列名]的新列.
I would like to take the log of some columns, and create new columns that are all named log[original column name].
下面的代码有效,但是如何将称为columnstolog
的向量传递给mutate?谢谢.
The code below works, but how can I pass the vector called columnstolog
into mutate? Thank you.
library(dplyr)
data(mtcars)
columnstolog <- c('mpg', 'cyl', 'disp', 'hp')
mtcars %>% mutate(logmpg = log(mpg))
mtcars %>% mutate(logcyl = log(cyl))
推荐答案
如果可以忍受_log
附加到原始列名的情况,请使用mutate_at
:
Use mutate_at
, if you can bear with _log
being appended to the original column names:
mtcars %>% mutate_at(columnstolog, funs(log = log(.)))
# mpg cyl disp hp drat wt qsec vs am gear carb mpg_log cyl_log disp_log hp_log
#1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 3.044522 1.791759 5.075174 4.700480
#2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 3.044522 1.791759 5.075174 4.700480
#3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 3.126761 1.386294 4.682131 4.532599
#4 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 3.063391 1.791759 5.552960 4.700480
#5 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2 2.928524 2.079442 5.886104 5.164786
# ...
这篇关于使用dplyr mutate基于列名称的向量创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文