0

I want to generate a set of 1000 random numbers between 1 and 20000 to then use those to subset a dataframe.

sample.int(20000, 2000, replace = TRUE) 

Then I want to copy/paste these numbers into this vector

df_sub <- df[,c(65,25,1,6000,1056, ...)] 

Is this possible?

2
  • No need to copy. just store them in a variable. ie var <- sample(20000, 1000, TRUE) then use the var to subset Commented Jul 15, 2022 at 22:41
  • 1
    No need to copy/paste, just sample directly in the indexing operation. For example, to randomly select 1000 rows between 1 and 20000 (with replacement): df[sample(1:20000, 1000, replace=T),] Commented Jul 15, 2022 at 22:41

3 Answers 3

2

No need to copy/paste, just sample directly in the indexing operation:

For example, to randomly select 1000 rows between 1 and 20000 (with replacement):

df[sample(1:20000, 1000, replace=T),] 
Sign up to request clarification or add additional context in comments.

Comments

1

Another option is to use dplyr's row_number() function to get the row id and sample the rows

 df %>% mutate(row_id=row_number()) %>% slice_sample(n=1000) 

To get the row ids

 df %>% mutate(row_id=row_number()) %>% slice_sample(n=1000) %>% pull(row_id) 

1 Comment

row_id is doing nothing in the first chunk of code other than add a column to the data.frame that contains the row number. The sampling is completely independent of the variable.
0

You can use clipr to write the vector to your clipboard.

library(dplyr) s <- sample.int(20000, 2000, replace = TRUE) vectorToCopy <- s %>% stringr::str_c(",", collapse=" ") %>% # sep each element by comma stringr::str_sub(., 1, nchar(.)-1) %>% # remove last comma str_c("c(", ., ")") # add parentheses clipr::write_clip(vectorToCopy) # write to clipboard 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.