2017-04-24 69 views
1

想象一下,我想在mtcars数据集中记录下列变量:disp,wtdrat。我想将它们保存为log_displog_wtlog_wt变换多个变量并用新名称保存

我可以把日志所有与保存:

cols <- c("disp","wt","drat") 
mtcars[cols] <- log(mtcars[cols]) 

然而,这将覆盖初始变量,我想保持。我怎样才能同时转换并保存为一个新变量?

+2

'mtcars [paste0(“log_”,cols)] < - log(mtcars [cols])' –

+0

感谢您的回答,我在考虑一些动态应用...但您的解决方案更整洁, ! – user3507584

回答

3

只是追加到分配的名称:

mtcars[paste("log",cols,sep="_")] <- log(mtcars[cols]) 
0

我们可以用tidyverse,使这个更具动感

library(tidyverse) 
f1 <- function(data, columns){ 
data %>% 
     transmute_at(columns, log) %>% 
     rename_all(funs(paste("log", columns, sep="_"))) %>% 
     bind_cols(data, .) 

} 

res <- f1(mtcars, cols) 
head(res, 3) 
# mpg cyl disp hp drat wt qsec vs am gear carb log_disp log_wt log_drat 
#1 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 5.075174 0.9631743 1.360977 
#2 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 5.075174 1.0560527 1.360977 
#3 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 4.682131 0.8415672 1.348073 

或者使用改变函数mutate_at

f2 <- function(data, columns){ 
data %>% 
     mutate_at(columns, funs(log = log(.))) %>% 
     rename_at(vars(matches('log')), funs(sub('(\\w+)_(\\w+)', "\\2_\\1", .))) 
} 
f2(mtcars, cols) 

注意:dplyr解决方案都使用标准dplyr语法

1

我真的很喜欢James & David所推荐的基本R方法。还有一个比较简单的解决方案dplyr:

library(dplyr) 
mutate_at(mtcars, setNames(cols, paste0("log_", cols)), log) 
# mpg cyl disp hp drat wt qsec vs am gear carb log_disp log_wt log_drat 
#1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 5.075174 0.9631743 1.360977 
#2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 5.075174 1.0560527 1.360977 
#3 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 4.682131 0.8415672 1.348073 

由于setNames(cols, paste0("log_", cols))创建一个名为向量,新列添加到结果,而不是修改现有列。