Replace “names” of columns of a data frame with different (new) names in another file in R

旧城冷巷雨未停 提交于 2019-12-23 23:34:41

问题


I have two data frames: One (dataframe A) is like as follows:

S.No    A1     A2    A3   A4     A6
  1      0      0     0    0      0
  2      2      4     7    7      9
  3      6      7     9    10     0

and so on.

Another (dataframe B) file is like as follows:

S.No   old_names      new_names
   1     A1              qq
   2     A2              ww
   3     A3              gg
   4     A4              zz
   5     A6              mm

Names of A need not be in same sequence as of B$old_names.

My new file should look like:

S.No    qq     ww    gg   zz     mm
  1      0      0     0    0      0
  2      2      4     7    7      9
  3      6      7     9    10     0

IS there any simpler way to do this in R without using for loop and comparing both files?

Any help would be greatly appreciated. Both files are too big.


回答1:


n <- names(df1)[-1]  # get rid of S.No

names(df1) <- c("S.No", as.character(df2$new_names)[match(n, df2$old_names)])


来源:https://stackoverflow.com/questions/17359937/replace-names-of-columns-of-a-data-frame-with-different-new-names-in-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!