For example:
temp <- data.frame(char = c("1", "2", "2", "2", "3", "3", "4", "4", "5"))
I want to have a variable to order my character between different numbers, Confusing?
Like this: 1 1 2 3 1 2 1 2 1
How can we create the variable like that?
Just two steps:
library(plyr)
temp2 <- ddply(temp, "char", nrow)
temp2
## char V1
## 1 1 1
## 2 2 3
## 3 3 2
## 4 4 2
## 5 5 1
temp$new_variable <- unlist(lapply(temp2$V1, function(x) seq(length.out = x)))
temp
## char new_variable
## 1 1 1
## 2 2 1
## 3 2 2
## 4 2 3
## 5 3 1
## 6 3 2
## 7 4 1
## 8 4 2
## 9 5 1
Why I do this?
Just for plot by ggplot2.
Welcome your advice and suggestion!
Just record, this article was posted at linkedin, and have 23 views to November 2021.