R: edit column values by using if condition -
i have data frame several columns. 1 of contains plotids aeg1, aeg2,..., aeg50, heg1, heg2,..., heg50, seg1, seg2,..., seg50. so, data frame has 150 rows. want change of these plotids, there aeg01, aeg02,... instead of aeg1, aeg2, ... so, want add "0" of column entries. tried using lapply, loop, writing function,... nothing did job. there error message:
in if (nchar(as.character(dat_merge$ep_plotid)) == 4) paste(substr(dat_merge$ep_plotid, ... : condition has length > 1 , first element used
so, last try:
plotid_func <- function(x) { if(nchar(as.character(dat_merge$ep_plotid))==4) paste(substr(dat_merge$ep_plotid, 1, 3), "0", substr(dat_merge$ep_plotid, 4, 4), sep="") } dat_merge$plotid <- sapply(dat_merge$ep_plotid, plotid_func)
therewith, wanted select column entries 4 digits. , selected entries, wanted add 0
. can me? dat_merge
name of data frame , ep_plotid
column want edit. in advance
just extract "string" portion , "numeric" portion , paste them after using sprintf
on numeric portion.
an example:
## "x" "column" of plot ids. here go 12 ## demonstrate 0 padding sounds ## you're looking x <- c(paste0("aeg", 1:12), paste0("heg", 1:12)) ## extract string values strings <- gsub("([a-z]+)(.*)", "\\1", x) ## extract numeric values nums <- gsub("([a-z]+)(.*)", "\\2", x) ## put them paste0(strings, sprintf("%02d", as.numeric(nums))) # [1] "aeg01" "aeg02" "aeg03" "aeg04" "aeg05" "aeg06" # [7] "aeg07" "aeg08" "aeg09" "aeg10" "aeg11" "aeg12" # [13] "heg01" "heg02" "heg03" "heg04" "heg05" "heg06" # [19] "heg07" "heg08" "heg09" "heg10" "heg11" "heg12"
Comments
Post a Comment