Command for renaming several variables

After reshaping my data, I have a large dataset with columnnames that look like this: 1_abc 1_vwxyz 2_abc 2_vwxyz

I would like to change my column names to look like this: abc_1 vwxyz_1 abc_2 vwxyz_2

My code looks like this:

data <- tibble("1_abc" = c(1,2,3), "1_vwxyz" = c(10,11,12), 
"2_abc" = c(1,1,2),"2_vwxyz" = c(9,11,15))

data_renamed <- data %>%
rename_(.dots=setNames(names(.), paste(substr(names(.), start=3, stop=nchar(names(.))), 
                                         substr(names(.), start=1, stop=1))))

I get this error:

Error in parse(text = x) : <text>:1:2: unexpected input
1: 1_
     ^
728x90

1 Answers Command for renaming several variables

Here's a solution in base R. You first take the column names as a character vector, convert them to a list of two-element character vectors, reverse the order of each and put them back together with _.

ll <- strsplit(colnames(data), pattern = "_")

# apply across this list of character vectors to reverse the order and concatenate
ll1 <- lapply(ll, function(x) paste(rev(x), collapse = "_"))

# unlist and assign them to the new data frame
data_renamed <- data
colnames(data_renamed) <- unlist(ll1)

#  A tibble: 3 x 4
#   abc_1 vwxyz_1 abc_2 vwxyz_2
#   <dbl>   <dbl> <dbl>   <dbl>
# 1     1      10     1       9
# 2     2      11     1      11
# 3     3      12     2      15

4 months ago