How to conditionally append incremented suffix to vector in R -
i have character vector in r reoccurring values:
vec <- c('22','22','22','45','45','45','56','67','67','67','89','90')
i want append _1, _2, _3 similar values in vector vector like:
vec <- c('22_1','22_2','22_3','45_1','45_2','45_3','56'_1,'67_1','67_2' ...
my question how increment conditionally ('56' singular , not need appended value). have tried writing loop , store occurrence counts in list, verbose , suspect there easier way of doing within apply family.
we can use ave
, sequence grouped 'vec', paste
original vector.
res <- paste(vec, ave(vec, vec, fun=seq_along), sep="_")
in case, need replace _1
elements have frequency of 1, use table
frequency, subset elements matches names
of 'table' having frequency 1 'res' , remove _
followed 0 or more characters sub
.
tbl <- table(vec) names(tbl)[tbl==1] i1 <- vec %in% names(tbl)[tbl==1] res[i1] <- sub('_.*', '', res[i1]) res #[1] "22_1" "22_2" "22_3" "45_1" "45_2" "45_3" "56" "67_1" "67_2" "67_3" #[11] "89" "90"
or can use make.unique
make.unique(vec, sep="_") #[1] "22" "22_1" "22_2" "45" "45_1" "45_2" "56" "67" "67_1" "67_2" #[11] "89" "90"
Comments
Post a Comment