2

In R, I want to find out the effect of character string length on computation time of a certain operation. For this, I need random character strings of different lengths. All I can think of now is:

cases1 <- letters[sample(15)] cases2 <- paste(letters[sample(15)], letters[sample(15)], sep="") cases3 <- paste(letters[sample(15)], letters[sample(15)], letters[sample(15)], sep="") 

How do I automate that? I don't want to keep copypasting... Or does anyone have a better idea?

1 Answer 1

2

Try

 n <- 3 do.call(`paste0`,as.data.frame(replicate(n, letters[sample(15)]))) 

If you want say 1:3

 n1 <- 1:3 lapply(n1, function(.n) do.call(`paste0`, as.data.frame(replicate(.n, letters[sample(15)])))) 

Or as @Berry showed in the comments

 apply(replicate(3, letters[sample(15)]), MARGIN=1, paste, collapse="") 
Sign up to request clarification or add additional context in comments.

2 Comments

Oh Yes. replicate is exactly what I need!! Thanks for making my day!
People scared of do.call might want also want to try apply(replicate(3, letters[sample(15)]), MARGIN=1, paste, collapse="")

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.