How to replace data.frame column names with a row in the corresponding lookup table in R

I have the following data.frame file:

set.seed(126) df <- data.frame(a=sample(c(1:100, NA), 10), b=sample(1:100, 10), c=sample(1:100, 10), d = c(1:10)) abcd 1 18 27 53 1 2 44 16 66 2 3 58 47 3 3 ... 

And the following lookup table:

 varnames <- data.frame(old = c("a", "b", "c"), new = c("dog", "cat", "mouse")) old new 1 a dog 2 b cat 3 c mouse 

What I'm trying to do is replace names(df) with the corresponding varnames$new ... If a names(df) not in varnames$old , save colname in df ...

The resulting data.frame file that I would like to return would look like this:

  dog cat mouse d 1 57 10 83 1 2 53 99 94 2 3 99 60 39 3 ... 

Any help is appreciated.

+6
source share
2 answers

How to use match() function

 mm <- match(names(df), varnames$old) names(df)[!is.na(mm)] <- as.character(varnames$new[na.omit(mm)]) head(df) # dog cat mouse d # 1 65 48 19 1 # 2 46 15 80 2 # 3 NA 47 84 3 # 4 68 34 46 4 # 5 23 75 42 5 # 6 92 87 68 6 

If you are interested, you can also use the dplyr rename() function

 library(dplyr) df %>% rename_(.dots=with(varnames, setNames(as.list(as.character(old)), new))) 

Or another option, the data.table package has a setnames function

 library(data.table) setnames(df, as.character(varnames$old), as.character(varnames$new)) 
+9
source

Another mapvalues() option from the plyr package:

 library(plyr) names(df) <- mapvalues(names(df), from = varnames$old, to = as.character(varnames$new)) 

If you use the dplyr package, you can call it with plyr::mapvalues() , so you do not need to load plyr on top of dplyr (which causes problems).

+2
source

Source: https://habr.com/ru/post/988535/


All Articles