0

I have the following vectors and a combined data frame which are objects feed to the expresion below.

x <- c(1,2,3,4)
y <- c(5,6,7,8)
z <- c(9,10,11,12)

h <- data.frame(x,y,z) 

D <- print (( rep ( paste ( "h[,3]" )  , nrow(h) )) , quote=FALSE )
# [1] h[,3] h[,3] h[,3] h[,3] 

DD <- c ( print ( paste ( (D) , collapse=","))) 
# "[1] h[,3],h[,3],h[,3],h[,3]"

DDD <- print ( DD, quote = FALSE ) 

# However when I place DDD in expand.grid it does not work

is(DDD)
[1] "character"  "vector"  "data.frameRowLabels"  "SuperClassMethod" 

Thus the expresion expand.grid(DDD) does not work. How could I get a process where I repeat n times a character element which represents an object as to obtain a vector of the number of repeated character elements which when placed in expand.grid works.

Barnaby
  • 1,472
  • 4
  • 20
  • 34

1 Answers1

3

It looks like you are trying to generate some R code then execute it. For your case, this will work:

# From your question
DDD
# [1] "h[,3],h[,3],h[,3],h[,3]"

# The code that you wish to execute, as a string
my_code <- paste("expand.grid(", DDD, ")")
# [1] "expand.grid( h[,3],h[,3],h[,3],h[,3] )"

# Execute the code
eval(parse(text = my_code))

I really recommend against doing this. See here for some good reasons why eval(parse(text = ...)) is a bad idea.

A more "R" solution to accomplish your task:

# Generate the data.frame, h
x <- c(1,2,3,4)
y <- c(5,6,7,8)
z <- c(9,10,11,12)
h <- data.frame(x,y,z) 

# Repeat the 3rd column 3 times, then call expand.grid
expand.grid(rep(list(h[,3]), times = 3))

# Alternatively, access the column by name
expand.grid(rep(list(h$z), times = 3))

By the way, I recommend looking at the help files for expand.grid - they helped me reach a solution to your problem quite quickly after understanding the arguments for expand.grid.

Community
  • 1
  • 1
ialm
  • 8,510
  • 4
  • 36
  • 48