if there are missing vectors such as 1, 1, 2, 3, 3, 5, 5, 7, 7, 7, 7, 7 and the number of numbers is different.
I just don't know how to fill in the missing numbers like 1, 1, 2, 3, 3, 4, 4, 5, 5, 5, 5 and rewrite the elements in descending order.
If you understand, please help us.
By the way, when I forced myself to write it down, it turned out to be the following, but it's a dirty code that I can't use on a practical basis.
vec<-c (1, 1, 2, 3, 3, 3, 5, 7, 7, 7, 7)
# put on a list of the same number
testlist<-list()
for (i in vec) {
testlist [[i]]<-vec [vec==i]
}
testlist #1, 2, 3, 5, 7th element with numeric value and 4th and 6th NULL
# delete and pack the NULL part
newlist<-testlist [ unique(vec)]
# Rename each element in the list with a continuous number
names(newlist)<-1:length(newlist)#The element in the list remains vec and retains the missing number, but names continues.
# Take out the names of the newlist, or the consecutive numbers, and click on the list element for that street number.
# rewrite the contents to match the number
finalist<-list()
for (in 1:length (newlist)) {
tmp<-names(newlist)[i]
finallist[[i]]<-rep(tmp, length(newlist[[i]]))
}
finallist
newvec<-unlist(finalist)
newvec<-as.numeric (newvec)
newvec#1,1,2,3,3,3,4,4,5,5,5
How about this one?I hope I can be of help.
vec<-c (1, 1, 2, 3, 3, 3, 5, 7, 7, 7, 7)
target1<-setdiff(1:max(vec), unique(vec))
for(i in 1:length(target1)){
vec [target1[i]<=vec]<-vec [target1[i]<=vec]-1
}
Additional
I'm sorry, but you've already received an elegant answer.Excuse me.
I think this is good when vec
is long.
cumsum(table(vec)>0) [vec]
as.numeric(as.factor(vec))
What do you think?
© 2024 OneMinuteCode. All rights reserved.