One option is to remove the numbers from the string names ( v1), create a named vector with the uniquesvalue 'v1', use it to match the values in 'v1' and create a new column 'ID'
v1 <- sub("\\d+", "", rownames(df))
transform(df, ID= setNames(c("Ctr", "P", "M"), unique(v1))[v1])[c(4, 1:3)]
Or another option factor
factor(sub("\\d+", "", rownames(df)), labels = c("Ctr", "P", "M"))
Or another option dplyr/tibble. We create the column "ID" from the row names ( rownames_to_columnfrom tibble), mutate"ID" for the new values using case_when.
library(dplyr)
library(tibble)
rownames_to_column(df, var="ID") %>%
mutate(ID = case_when(.$ID %in% c("a1", "a2", "a3") ~ "Ctr",
.$ID %in% c("b1", "b2", "b3") ~ "P",
TRUE ~ "M"))
akrun source
share