转换多个变量并使用新名称保存它们

时间:2017-04-24 12:49:58

标签: r

想象一下,我想在mtcars数据集中记录以下变量:dispwtdrat。我想将其保存为log_displog_wtlog_wt

我可以记录所有日志并保存:

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

然而,这会覆盖我想保留的初始变量。我怎样才能同时转换并保存为新变量?

3 个答案:

答案 0 :(得分:3)

只需附加作业中的名称:

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

答案 1 :(得分:2)

我非常喜欢James&amp; amp;大卫。还有一个相对简单的dplyr解决方案:

{
  "name": "angular-quickstart",
  "version": "1.0.0",
  "description": "QuickStart package.json from the documentation, supplemented with testing support",

  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@angular/common": "~4.0.0",
    "@angular/compiler": "~4.0.0",
    "@angular/core": "~4.0.0",
    "@angular/forms": "~4.0.0",
    "@angular/http": "~4.0.0",
    "@angular/platform-browser": "~4.0.0",
    "@angular/platform-browser-dynamic": "~4.0.0",
    "@angular/router": "~4.0.0",

    "angular-in-memory-web-api": "~0.3.0",
    "systemjs": "0.19.40",
    "core-js": "^2.4.1",
    "rxjs": "5.0.1",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "concurrently": "^3.2.0",
    "lite-server": "^2.2.2",
    "typescript": "~2.1.0",

    "canonical-path": "0.0.2",
    "tslint": "^3.15.1",
    "lodash": "^4.16.4",
    "jasmine-core": "~2.4.1",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~4.0.14",
    "rimraf": "^2.5.4",

    "@types/node": "^6.0.46",
    "@types/jasmine": "2.5.36"
  },
  "repository": {}
}

由于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 创建了一个命名向量,因此新列将添加到结果中,而不是修改现有列。

答案 2 :(得分:1)

我们可以使用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语法