Add a prefix to column names
Solution 1:
You have misread the help file. Here's the argument to look at:
do.NULL
: logical. If FALSE
and names are NULL
, names are created.
Notice the and in that description. Your names are no longer NULL
, so using prefix won't work.
Instead, use something like this:
> m2 <- cbind(1,1:4)
> colnames(m2) <- c("x","Y")
> colnames(m2) <- paste("Sub", colnames(m2), sep = "_")
> m2
Sub_x Sub_Y
[1,] 1 1
[2,] 1 2
[3,] 1 3
[4,] 1 4
Solution 2:
I will add a tidyverse
approach to this problem, for which you can both add suffix and prefix to all column names. The following adds a prefix in a dplyr
pipe.
dplyr 1.0.2 and beyond
library(dplyr)
df <- data.frame(x = c(1, 2), y = c(3, 4))
## Adding prefixes
df %>% rename_with( ~ paste0("a", .x))
## Adding suffixes
df %>% rename_with( ~ paste0(.x, "a"))
If you want to have separators such as underline, you can use paste
as well with the sep
argument.
Before dplyr 1.0.2 update
library(dplyr)
df <- data.frame(x = c(1, 2), y = c(3, 4))
df %>% rename_all( ~ paste0("a", .x))
Adding suffix is easier.
df %>% rename_all(paste0, "a")
Solution 3:
The updated tidyverse
method (with dplyr 1.0.2
) uses rename_with()
as the rename_all()
function has been superseded.
iris %>% rename_with( ~ paste("Sub", .x, sep = "_"))