【问题标题】:Transform list with different sized vectors to flat vector将具有不同大小向量的列表转换为平面向量
【发布时间】:2012-08-07 15:31:30
【问题描述】:

我正在努力用向量分析一个相当复杂的列表中的值。 它是一个包含将 ARIMA 测试应用于多个时间序列的系数(=向量)的列表。

这些系数向量可能为空 (numeric(0)),或大小不同。一个例子:

> test <- list(numeric(0),c(ma1=0.7712434), c(ar1=0.6438842, ar2=-0.3112884))
> test
[[1]]
numeric(0)

[[2]]
      ma1 
0.7712434 

[[3]]
       ar1        ar2 
 0.6438842 -0.3112884 

例如,我希望能够轻松选择所有“ar”或“ar1”术语(根据名称进行选择)。我正在努力处理这个复杂的列表。所以我认为最简单的解决方案是将这个向量列表转换为单个向量(忽略空数字)。

对于上面的示例导致:

> c(ma1=0.7712434, ar1=0.6438842, ar2=-0.3112884)
       ma1        ar1        ar2 
 0.7712434  0.6438842 -0.3112884

谁能帮帮我?

注意: 我能够根据它们的名称计算出 AR 术语的数量,见下文。但我无法使用它来提取这些术语的实际值。

tempFunName <- function(vec, name) { substr(names(vec),1,2) == name } # info on coef types
termType <- "ar" # all names starting with "ar"
sum(sapply(lapply(test, tempFunName, name=termType), sum, simplify=TRUE)) # all names starting with "ar"

【问题讨论】:

    标签: r


    【解决方案1】:

    一种方法是:

    unlist(test)[grep("^ar", names(unlist(test)))]
    

    unlist() 只是将列表变成一个向量,然后我们可以从那里通过grep 进行名称匹配的子集。 ^ 表示搜索名称开头的模式。

    如果你想保持列表形式的输出,你可以试试:

    lapply(test, function(x) x[grep("^ar", names(x))])
    

    更新:示例

    注意为了便于说明,我在您的示例数据中添加了更多变量。

    test <- list(numeric(0),
                 c(ma1 = 0.7712434, star = .001),
                 c(ar1 = 0.6438842, ar2 = -0.3112884, par = 0.12345))
    lapply(test, function(x) x[grep("ar", names(x))])
    # [[1]]
    # numeric(0)
    # 
    # [[2]]
    #  star 
    # 0.001 
    # 
    # [[3]]
    #       ar1        ar2        par 
    # 0.6438842 -0.3112884  0.1234500 
    lapply(test, function(x) x[grep("^ar", names(x))])
    # [[1]]
    # numeric(0)
    # 
    # [[2]]
    # named numeric(0)
    # 
    # [[3]]
    #       ar1        ar2 
    # 0.6438842 -0.3112884 
    unlist(lapply(test, function(x) x[grep("^ar", names(x))]))
    #       ar1        ar2 
    # 0.6438842 -0.3112884 
    

    【讨论】:

    • @ttmaccer 和@mrdwab;感谢您的回答。 unlistdo.call("c", ...) 的结果相同。出于计算时间的原因,我选择了unlist 解决方案:unlist = 0.72 的 system.time,do.call = 1.31。虽然两者都需要一点时间,但我会选择最快的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2013-04-07
    • 2011-07-07
    相关资源
    最近更新 更多