0

My question is a variation of this question. What I want is to add a prefix to a vector or column names (which is a subset of all column names). I tried to expand the solution from the link to more columns as follows, but got stuck.

Data:

m2 <- cbind(1,1:4,4:1)
colnames(m2) <- c("x","y","z")

     x y z
[1,] 1 1 4
[2,] 1 2 3
[3,] 1 3 2
[4,] 1 4 1

colnames(m2)[colnames(m2) == c("x","z")] <- paste("Sub", colnames(m2)[colnames(m2) == c("x","z")], sep = "_")

Warning messages:
1: In colnames(m2) == c("x", "z") :
  longer object length is not a multiple of shorter object length
2: In colnames(m2) == c("x", "z") :
  longer object length is not a multiple of shorter object length

m2
     Sub_x y z
[1,]     1 1 4
[2,]     1 2 3
[3,]     1 3 2
[4,]     1 4 1

The code gives two warnings and only changes one column.

Desired output:

m2 <- cbind(1,1:4,4:1)
colnames(m2) <- c("x","y","z")
colnames(m2)[1] <- paste("Sub", colnames(m2)[1], sep = "_")
colnames(m2)[3] <- paste("Sub", colnames(m2)[3], sep = "_")
m2

     Sub_x y Sub_z
[1,]     1 1     4
[2,]     1 2     3
[3,]     1 3     2
[4,]     1 4     1
Tom
  • 2,173
  • 1
  • 17
  • 44

1 Answers1

0

Alternative solution using dplyr

library(dplyr)
m2 %>% 
  as_tibble() %>% 
  rename_with(.cols = c("x", "z"), ~ stringr::str_c("Sub_", .))
Julian
  • 6,586
  • 2
  • 9
  • 33