2016-02-13 30 views
0

我有以下向量和一個組合的數據框,它們是以下表達式的對象。使用expand.grid和對象

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" 

因此expresion expand.grid(DDD)不起作用。我怎麼能得到一個過程,我重複n次代表一個對象的字符元素,以獲得當放置在expand.grid工作中時重複字符元素的數量的向量。

回答

3

它看起來像你試圖生成一些R代碼,然後執行它。對於你的情況,這將工作:

# 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)) 

我真的建議這樣做。 eval(parse(text = ...))是個不錯的主意,請參閱here

更多的「R」的解決方案來完成你的任務:

# 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)) 

順便說一句,我建議看幫助文件expand.grid - 他們幫助我理解了之後很快達成解決您的問題參數爲expand.grid

+0

上述效率更高的代碼採用了點數,非常感謝 – Barnaby

+1

'replicate'比'list' +'rep'稍微更直接。 'expand.grid(replicate(3,h [,3],FALSE))'。 – A5C1D2H2I1M1N2O1R2T1