My question is that I wish to use pipes to simplify my codes. But in one of the steps, I only want to extract and continue with one of the elements in my data. Please see the code below for more details
data1 <-coef(df)
data2 <-as.data.frame(data1$a)
So I need to run a function called 'coef', that will return a list of results, say, 'a,b,c,d', but I am only interested in 'a'. And normally I will store the full results, then store the results that I'm interested using a dollar sign $. But I wonder if I can also do in pipe,something similar to the codes below, but it apparently wouldn't work for now.
data2<-df %>%
coef() %>%
select(a) %>%
as.data.frame ()
CodePudding user response:
coef()
gives you a vector, so $
is not applicable. But you may use getElement()
.
lm(mpg ~ am hp, mtcars) |>
coef() |>
getElement('am')
# [1] 5.277085
Works also with magrittr
pipes %>%
of course.
CodePudding user response:
We assume that the question is asking how to extract a column from a data frame. Later we assume the alternative that it is asking how to pick out one coefficient from the built-in coef
acting on an lm
model. Next time please provide a complete reproducible code and inputs so we can be sure what is being asked.
Here are several ways using the built-in BOD data frame.
library(magrittr)
BOD %$% Time
## [1] 1 2 3 4 5 7
BOD %>% extract2("Time")
## [1] 1 2 3 4 5 7
# can use library(magrittr) or library(dplyr) for any of these
BOD %>% with(Time)
## [1] 1 2 3 4 5 7
BOD %>% .$Time
## [1] 1 2 3 4 5 7
BOD %>% .subset2("Time")
## [1] 1 2 3 4 5 7
BOD %>% .[["Time"]]
## [1] 1 2 3 4 5 7
library(dplyr)
BOD %>% pull(Time)
## [1] 1 2 3 4 5 7
If what was meant in the question was that coef
is extracting coefficients from an lm model and we want one of them then we have the following which are the same except that in some cases we need to add as.list
to the pipeline.
library(magrittr)
# this is used by all the pipelines below
co <- BOD %>% lm(demand ~ Time, .) %>% coef
co %>% as.list %$% Time
## [1] 1.721429
co %>% extract2("Time")
## [1] 1.721429
# can use library(magrittr) or library(dplyr) for any of these
co %>% as.list %>% with(Time)
## [1] 1.721429
co %>% as.list %>% .$Time
## [1] 1.721429
co %>% .subset2("Time")
## [1] 1.721429
co %>% .[["Time"]]
## [1] 1.721429