r - lapply 2 functions in one command -
i want alter names in info frame df
> names(df)[17:26] [1] "x1." "x2." "x3." "x4." "x5." "x6." "x7." "x8." "x9." "x10." i want "x" -> "reach" , remove dots. used lapply:
change <- function(d){ gsub("x","reach",d) gsub("\\.","",d) } <- as.character(lapply(names(df)[17:26], change)) but "x" didn't change. why?
> [1] "x1" "x2" "x3" "x4" "x5" "x6" "x7" "x8" "x9" "x10"
you can in single gsub using references (the parenthesised parts of pattern expression).
x <- names(df)[17:26] gsub( "x([0-9]+)." , "reach\\1" , x ) # [1] "reach1" "reach2" "reach3" "reach4" "reach5" "reach6" "reach7" "reach8" "reach9" "reach10" we match digits in names vector using [0-9]+ , surrounding them in parentheses create known reference. can refer stuff matched within parentheses reference. since first set of parentheses, it's reference \\1. if had set of braces refer \\2. match x, numbers , .. replace reach , numbers matched within parentheses referring reference using \\1.
i hope explanation makes sense! isn't clearest.
r data.frame lapply names
No comments:
Post a Comment