【问题标题】:select and extract a vector of indices from a data frame从数据框中选择并提取索引向量
【发布时间】:2017-02-23 15:25:11
【问题描述】:

我有一个数据框和一个向量:

parameters <- data.frame(index = c(3:12, 15:18, 23:25), variable = c("Pin", 
                      "Pout", "Tin", "speed", "D", "L", "Cin_h", "Cout_h", "VdA", 
                      "preswirl", "mu", "mol_weight", "Cp", "Z", "ffactor_N", 
                      "ffactor_M", "nfreqs"),
                      value = c(65, 4, 16.85, 7900, 110, 60, 0.1975, .1875, 2.31,
                                0.2, 0.0011877, 22.0, 1.4, 1.0, 0.0785, -0.1101,
                                30))
temp <- runif(100)

我想从parameters 读取索引向量,并将它们用作索引向量以读入temp。例如,假设我想要变量nfreqsPout对应的索引:

library(dplyr)
index_vector <- parameters %>% filter(variable %in% c("Pout","nfreqs")) %>% select(index)

问题是现在index_vector 不是一个向量,而是一个数据框,因此我不能用它来读入temp

> temp[index_vector]
Error in temp[index_vector] : invalid subscript type 'list'

temp[index_vector$index] 当然可以。但我想知道是否可以在dplyr 调用期间直接提取我感兴趣的向量,即通过适当修改

index_vector <- parameters %>% filter(variable %in% c("Pout","nfreqs")) %>% select(index)

【问题讨论】:

    标签: r indexing dataframe


    【解决方案1】:

    我们需要提取列

    temp[index_vector$index]
    #[1] 0.2784451 0.1061800
    

    但是,如果我们需要在%&gt;% 内执行此操作

    library(magrittr)
    parameters %>% 
        filter(variable %in% c("Pout","nfreqs")) %>%
        .$index %>%
        extract(temp, .)
    #[1] 0.2784451 0.1061800
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      • 2019-09-10
      • 2020-04-27
      • 1970-01-01
      相关资源
      最近更新 更多