Create n unique names with R
I want to generate n unique names using R. This is the code I have right now:
library(randomNames)
set.seed(6232015)
gen.names <- function(n){
while(n>0){
names <- unique(randomNames(n=n))
n <- n - length(names)
names2 <- c(unique(randomNames(n=n)), names)
n <- n - length(names2)
}
return(names2)
}
nombres<- gen.names(n = 40000)
Instead of getting 40,000, I get 39999. If I ask for less than 40,000, I get that number. What's wrong with my code?
Thank!
+3
source to share
2 answers
Thanks @jeremycg!
This is my solution after reading your answer:
set.seed(6232015)
gen.names <- function(n){
names <- unique(randomNames(n=n))
need <- n - length(names)
while(need>0){
names <- unique(c(randomNames(n=need), names))
need <- n - length(names)
}
return(names)
}
nombres<- gen.names(n = 100000)
0
source to share
You get unique names in the second call, which results in name loss. Then n is evaluated, allowing you to exit the while loop.
Go through it:
names <- unique(randomNames(n=n))
n <- n - length(names)
you got 38986 unique names and n is now 1014
Now:
names2 <- c(unique(randomNames(n=n)), names)
n <- n - length(names2)
You have 1013 new unique names giving 39999 common names in names2 and n is now 1014 - 39999 = -38985
You hit the end of the loop and exit when you are less than 1 and return your values ββwith 1 missing name.
Here's a hacky solution producing 2000 additional names, then checking for a loop:
gen.names <- function(n){
names<-c()
while(length(names)<n){
names <- unique(c(randomNames(n=n+2000),names))
}
return(names[1:n])
}
+1
source to share