使用dplyr mutate根据一列列名的向量创建新的列

4

我希望对一些列取对数,并创建新的列,这些列的名称都是原始列名前加上log。

下面的代码可以实现,但是如何将名为columnstolog的向量传递给mutate函数呢?谢谢。

library(dplyr)
data(mtcars)

columnstolog <- c('mpg', 'cyl', 'disp', 'hp')

mtcars %>% mutate(logmpg = log(mpg))
mtcars %>% mutate(logcyl = log(cyl))
3个回答

10

使用mutate_at,如果您可以忍受将_log附加到原始列名称中:

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
# ...

3
忽略“使用dplyr”部分...
require(data.table)    

mtcars <- as.data.table(mtcars)

mtcars[, paste0('log', columnstolog) := lapply(.SD, log), .SDcols = columnstolog]

2

您还可以使用dplyr包中的rowwise

mtcars %>% 
   rowwise %>%
   mutate(logmpg = log(mpg),
       logcyl = log(cyl))


# A tibble: 32 x 13
     mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb   logmpg   logcyl
   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>    <dbl>    <dbl>
 1  21.0     6 160.0   110  3.90 2.620 16.46     0     1     4     4 3.044522 1.791759
 2  21.0     6 160.0   110  3.90 2.875 17.02     0     1     4     4 3.044522 1.791759
 3  22.8     4 108.0    93  3.85 2.320 18.61     1     1     4     1 3.126761 1.386294
 4  21.4     6 258.0   110  3.08 3.215 19.44     1     0     3     1 3.063391 1.791759
 5  18.7     8 360.0   175  3.15 3.440 17.02     0     0     3     2 2.928524 2.079442
 6  18.1     6 225.0   105  2.76 3.460 20.22     1     0     3     1 2.895912 1.791759
 7  14.3     8 360.0   245  3.21 3.570 15.84     0     0     3     4 2.660260 2.079442
 8  24.4     4 146.7    62  3.69 3.190 20.00     1     0     4     2 3.194583 1.386294
 9  22.8     4 140.8    95  3.92 3.150 22.90     1     0     4     2 3.126761 1.386294
10  19.2     6 167.6   123  3.92 3.440 18.30     1     0     4     4 2.954910 1.791759
# ... with 22 more rows

谢谢,@blazej。有没有办法添加一个向量,例如:columnstolog <- c('mpg', 'cyl', 'disp', 'hp')然后使用rowwise和mutate对该向量中的所有列取对数? - Jeremy K.
哦,抱歉 - 没有注意到 columnstolog 是必填项。虽然这可能是可能的,但我无法想出一个可行的示例。 - blazej

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接