【问题标题】:using expand.grid with objects将 expand.grid 与对象一起使用
【发布时间】:2016-05-24 07:12:20
【问题描述】:

我有以下向量和一个组合数据框,它们是提供给下面表达式的对象。

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" 

因此表达式 expand.grid(DDD) 不起作用。我怎样才能获得一个过程,其中我重复 n 次表示对象的字符元素以获得重复字符元素数量的向量,当放置在 expand.grid 中时该向量起作用。

【问题讨论】:

    标签: r


    【解决方案1】:

    看起来您正在尝试生成一些 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))
    

    我真的建议反对这样做。请参阅 here 了解为什么 eval(parse(text = ...)) 是一个坏主意的一些充分理由。

    完成任务的更“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 的参数后,它们帮助我很快找到了解决您问题的方法。

    【讨论】:

    • replicatelist + rep 更直接一些。 expand.grid(replicate(3, h[, 3], FALSE)).
    猜你喜欢
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多