R:在数据框中重命名变量的子集 [英] R: rename subset of variables in data frame

查看:89
本文介绍了R:在数据框中重命名变量的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重命名数据框中的大多数变量,而我的方法并没有给我留下深刻的印象.

I'm renaming the majority of the variables in a data frame and I'm not really impressed with my method.

因此,SO上的任何人有没有比下面介绍的仅使用基础的方法更聪明或更快速的方法?

Therefore, does anyone on SO have a smarter or faster way then the one presented below using only base?

    data(mtcars)
  # head(mtcars)


  temp.mtcars <- mtcars
  names(temp.mtcars) <- c((x <- c("mpg", "cyl", "disp")), 
                           gsub('^', "baR.", setdiff(names (mtcars),x)))
  str(temp.mtcars)
  'data.frame': 32 obs. of  11 variables:
   $ mpg     : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
   $ cyl     : num  6 6 4 6 8 6 8 4 4 6 ...
   $ disp    : num  160 160 108 258 360 ...
   $ baR.hp  : num  110 110 93 110 175 105 245 62 95 123 ...
   $ baR.drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
   $ baR.wt  : num  2.62 2.88 2.32 3.21 3.44 ...
   $ baR.qsec: num  16.5 17 18.6 19.4 17 ...
   $ baR.vs  : num  0 0 1 1 0 1 0 1 1 1 ...
   $ baR.am  : num  1 1 1 0 0 0 0 0 0 0 ...
   $ baR.gear: num  4 4 4 3 3 3 3 4 4 4 ...
   $ baR.carb: num  4 4 1 1 2 1 4 2 2 4 ...

推荐答案

我会使用ifelse:

names(temp.mtcars) <- ifelse(names(mtcars) %in% c("mpg", "cyl", "disp"),
                             names(mtcars),
                             paste("bar", names(mtcars), sep = "."))

这篇关于R:在数据框中重命名变量的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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