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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

replicate is slightly more direct than list + rep. expand.grid(replicate(3, h[, 3], FALSE)).

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.