Reputation: 5646
I have a data frame and a vector:
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)
I want to read a vector of indices from parameters
, and use them as an index vector to read into temp
. For example, let's assume I want the index corresponding to the variable nfreqs
and Pout
:
library(dplyr)
index_vector <- parameters %>% filter(variable %in% c("Pout","nfreqs")) %>% select(index)
The problem is that now index_vector
is not a vector, but a dataframe, thus I can't use it to read into temp
:
> temp[index_vector]
Error in temp[index_vector] : invalid subscript type 'list'
temp[index_vector$index]
works, of course. But I was wondering if I could directly extract the vector I'm interested in, during the dplyr
call, i.e., by suitably modifying
index_vector <- parameters %>% filter(variable %in% c("Pout","nfreqs")) %>% select(index)
Upvotes: 1
Views: 1180
Reputation: 886938
We need to extract the column
temp[index_vector$index]
#[1] 0.2784451 0.1061800
But, if we need to do this within the %>%
library(magrittr)
parameters %>%
filter(variable %in% c("Pout","nfreqs")) %>%
.$index %>%
extract(temp, .)
#[1] 0.2784451 0.1061800
Upvotes: 1