I used @earino's answer in front of me, but found that it might be unsafe. If the name (s) of the specified vector does not contain the column names of the data frame, these column names are silently replaced by NA and this is certainly not what you want.
d1 <- data.frame(A = 1:10, B = letters[1:10], stringsAsFactors = FALSE) rename_vec <- c("B" = "var2", "C" = "var3") names(d1) <- rename_vec[names(d1)] str(d1) #> 'data.frame': 10 obs. of 2 variables: #> $ NA : int 1 2 3 4 5 6 7 8 9 10 #> $ var2: chr "a" "b" "c" "d" ...
The same thing can happen if you run names(d1) <- rename_vec[names(d1)] twice, because when you run it a second time, none of colnames(d1) has names(rename_vec) .
names(d1) <- rename_vec[names(d1)] str(d1) #> 'data.frame': 10 obs. of 2 variables: #> $ NA: int 1 2 3 4 5 6 7 8 9 10 #> $ NA: chr "a" "b" "c" "d" ...
A safer way would be to replace the string with column names, for example str_replace_all() from the package {stringr}.
We just need to select the columns that are in the data frame and in the renaming vector.
d2 <- data.frame(B1 = 1:10, B = letters[1:10], stringsAsFactors = FALSE) sel <- is.element(colnames(d2), names(rename_vec)) names(d2)[sel] <- rename_vec[names(d2)][sel] str(d2) #> 'data.frame': 10 obs. of 2 variables: #> $ B1 : int 1 2 3 4 5 6 7 8 9 10 #> $ var2: chr "a" "b" "c" "d" ...
UPDATE: I initially had a solution that included replacing the string, which also turned out to be unsafe, because it allowed a partial match. I think this is better.
dpprdan
source share