0

I found this solution to give columns prefixes:

m2 <- cbind(1,1:4)
colnames(m2) <- c("x","Y")
colnames(m2) <- paste("Sub", colnames(m2), sep = "_")
m2

What I would like to do instead, is paste the prefix only two column x, by using its column name.

Among several other things I tried:

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

What would be the best way to do this?

Desired output:

colnames(m2)[1] <- paste("Sub", colnames(m2)[1], sep = "_")

EDIT

Using Maël's solution I tried to do the following:

m2 <- cbind(1,1:4,4:1)
colnames(m2) <- c("x","y","z")
colnames(m2)[colnames(m2) == c("x","z")] <- paste("Sub", colnames(m2)[colnames(m2) == c("x","z")], sep = "_")
Tom
  • 2,173
  • 1
  • 17
  • 44

1 Answers1

2
m2 <- cbind(1,1:4)
colnames(m2) <- c("x","Y")

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

m2
#     Sub_x Y
#[1,]     1 1
#[2,]     1 2
#[3,]     1 3
#[4,]     1 4

with more than one value, use %in%:

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

     Sub_x y Sub_z
[1,]     1 1     4
[2,]     1 2     3
[3,]     1 3     2
[4,]     1 4     1
Maël
  • 45,206
  • 3
  • 29
  • 67
  • Thank you for your answer Maël, but it still refers to the index for storage.. Is it possible to refer to a string or vector of strings there as well? – Tom Apr 11 '22 at 10:18
  • Right, see my edit. – Maël Apr 11 '22 at 10:19
  • Hey Maël, I tried to expand on your solution (see EDIT, please note that `Y` became `y`), because my actual data has more columns, but without much success. Would it be easy to adapt your answer to my edit or would you suggest me to ask a separate question? – Tom Apr 11 '22 at 12:52
  • Link to variation of this question: https://stackoverflow.com/questions/71829262/referring-to-multiple-columns-by-name – Tom Apr 11 '22 at 14:06
  • 1
    Hej @Tom, see my edit. – Maël Apr 11 '22 at 14:25