Reputation: 2253
I have my dataset t
comprising 1850 columns. Most of these contain "fu1"
in their name. I want to replace all fu1
to "v1"
A sample of t
looks like:
> t
symp_pre_rh_fu1___1 symp_pre_rh_fu1___2 symp_pre_rh_fu1___3 symp_pre_rh_fu1___4
1 0 0 0 0
2 1 0 0 0
3 1 1 0 1
4 1 1 0 0
5 0 0 0 0
But I want it to print:
> t
symp_pre_rh_v1___1 symp_pre_rh_v1___2 symp_pre_rh_v1___3 symp_pre_rh_v1___4
1 0 0 0 0
2 1 0 0 0
3 1 1 0 1
4 1 1 0 0
5 0 0 0 0
I would prefer a solution in dplyr
if possible.
t <- structure(list(symp_pre_rh_fu1___1 = c(0L, 1L, 1L, 1L, 0L), symp_pre_rh_fu1___2 = c(0L,
0L, 1L, 1L, 0L), symp_pre_rh_fu1___3 = c(0L, 0L, 0L, 0L, 0L),
symp_pre_rh_fu1___4 = c(0L, 0L, 1L, 0L, 0L), symp_pre_rh_fu1___5 = c(0L,
0L, 1L, 0L, 0L)), row.names = c(NA, -5L), class = "data.frame")
Upvotes: 0
Views: 40
Reputation: 24888
@Onyambu provided the easy way. A tidyverse approach might be to use dplyr::rename_all
.
The second argument is .funs
which will accept a function to apply to the names. In this case, we can use stringr::str_replace
to replace the string.
library(dplyr)
library(stringr)
t %>% rename_all(~str_replace(.,"fu1","v1"))
symp_pre_rh_v1___1 symp_pre_rh_v1___2 symp_pre_rh_v1___3 symp_pre_rh_v1___4 symp_pre_rh_v1___5
1 0 0 0 0 0
2 1 0 0 0 0
3 1 1 0 1 1
4 1 1 0 0 0
5 0 0 0 0 0
Upvotes: 1