Reputation: 63
I have a problem very similar to this one: Adding a prefix to column names. I want to add a prefix to the column name - the only difference is, that I dont want to add the prefix to every column I have. Here the same minimum, reproducible example as in the question mentioned above:
m2 <- cbind(1,1:4)
colnames(m2) <- c("x","Y")
Resulting in:
x Y
[1,] 1 1
[2,] 1 2
[3,] 1 3
[4,] 1 4
The code for adding a prefix "Sub" to both columns would look like this (as suggested by the user A5C1D2H2I1M1N2O1R2T1):
colnames(m2) <- paste("Sub", colnames(m2), sep = "_")
Resulting in:
Sub_x Sub_Y
[1,] 1 1
[2,] 1 2
[3,] 1 3
[4,] 1 4
How can I add a prefix "Sub" only to the first column? I tried the following:
colnames(m2[,1]) <- paste("Sub", colnames(m2[,1]), sep = "_")
Result of the code: No Warning, no error but no prefix as well. Any suggestions? Besides base r any suggestions using dplyr are appreciated as well. Please let me know if you need any further information. Thanks in advance.
Upvotes: 1
Views: 731
Reputation: 33488
Also paste()
accepts vectors so you could do:
colnames(m2) <- paste0(c("Sub_", ""), colnames(m2))
Upvotes: 0
Reputation: 39858
With dplyr
, you can do:
m2 %>%
as.data.frame() %>%
rename_at(1, ~ paste("Sub", ., sep = "_"))
Sub_x Y
1 1 1
2 1 2
3 1 3
4 1 4
Upvotes: 1
Reputation: 3791
Try this:
colnames(m2)[1] <- paste0("Sub", "_", colnames(m2)[1])
# or if you prefer paste
#colnames(m2)[1] <- paste("Sub", colnames(m2)[1], sep = "_")
Upvotes: 2