1

I am trying to create a dataframe based on user-provided input. The user will decide the number of variables to be included in the dataframe.

Below I provide the codes that do what I am after. What I want to do is to create a function that does this same task.

var1 <- c(1:6)
var2 <- c(1:6)
var3 <- c(1:6)

var1 <- sample(var1, 10, replace = TRUE)
var2 <- sample(var2, 10, replace = TRUE)
var3 <- sample(var3, 10, replace = TRUE)

mydata <- data.frame(var1, var2, var3)

I expect the output below.

   var1 var2 var3
1     4    1    3
2     2    5    1
3     5    6    2
4     4    5    2
5     5    3    3
6     5    5    2
7     1    3    6
8     3    5    5
9     2    4    1
10    5    5    5
2
  • so the only parameter provided by the user is a single number? (or, if not, what parameters are provided by the user?) Commented Aug 15, 2019 at 20:30
  • Yes, that is right. Commented Aug 15, 2019 at 20:31

2 Answers 2

1
make_df <- function(n, x = 1:6, nrow = 10, var_prefix = 'var'){
  out <- as.data.frame(matrix(sample(x, nrow*n, TRUE), nrow, n))
  # or: out <- as.data.frame(replicate(n, sample(x, nrow, TRUE), simplify = F))
  setNames(out, paste0(var_prefix, seq_along(out)))
}


make_df(5)
#    var1 var2 var3 var4 var5
# 1     5    3    1    1    3
# 2     2    2    4    4    3
# 3     2    2    3    6    3
# 4     3    2    6    4    4
# 5     3    1    6    1    1
# 6     6    2    4    2    2
# 7     4    6    6    5    6
# 8     4    3    2    4    6
# 9     4    6    6    4    4
# 10    4    2    1    5    1

make_df(n = 5, x = 10:20, nrow = 4, var_prefix = 'col')
#   col1 col2 col3 col4 col5
# 1   16   13   16   10   11
# 2   17   10   12   12   16
# 3   16   11   10   11   15
# 4   15   14   13   14   11
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. What if I want the user to also decide whether s/he wants to have 1:6, 1:10, 1:2 etc.?
0
ncol = 3 # user input

nrow = 10 # your configuration
x = 1:6

# make the data frame
as.data.frame(matrix(sample(x, size = ncol * nrow, replace = TRUE), ncol = ncol))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.