0

I have the following data

data <- data.frame(c=1:5, ID=0,a=2,b=5:9)
naming <- data.frame(short=c("a","b","c", "d", "e"), long=c("aa","bb","cc", "dd", "ee"))

I would like to rename the columns in data frame data from c,ID,b,a to cc,ID,bb,aa

I tried:

colnames(data) <- naming[match(naming$short, colnames(data)),2]

but this does not work, as both vectors are not of the same length, further, I would like to keep the column names in data, that are not in naming.

Any suggestions? Basically its hlookup function from Excel, but due to large data files I cannot do this in Excel.

Justas Mundeikis
  • 935
  • 1
  • 10
  • 19

2 Answers2

2

Base R:

matches <- match(names(data), naming$short)
matches
# [1]  3 NA  1  2
ifelse(is.na(matches), names(data), naming$long[matches])
# [1] "cc" "ID" "aa" "bb"
names(data) <- ifelse(is.na(matches), names(data), naming$long[matches])
data
#   cc ID aa bb
# 1  1  0  2  5
# 2  2  0  2  6
# 3  3  0  2  7
# 4  4  0  2  8
# 5  5  0  2  9
r2evans
  • 141,215
  • 6
  • 77
  • 149
1

using dplyr 's rename_at and passing an anonymous functions seems to fit your purposes

require(dplyr)

data <- data.frame(c=1:5, ID=0,a=2,b=5:9)

data 
#   c ID a b
# 1 1  0 2 5
# 2 2  0 2 6
# 3 3  0 2 7
# 4 4  0 2 8
# 5 5  0 2 9

cols_iwant_to_rename <- c("a","b","c")



data <- 
data %>% rename_at(cols_iwant_to_rename , function(x) paste0(x, x)) 

data 

#    cc ID aa bb
# 1  1  0  2  5
# 2  2  0  2  6
# 3  3  0  2  7
# 4  4  0  2  8
# 5  5  0  2  9
Mouad_Seridi
  • 2,666
  • 15
  • 27