Home > Net >  What is the solution to the error I am having while using sapply function?
What is the solution to the error I am having while using sapply function?

Time:09-29

My code :

t<-
mtcars %>%
split(.$cyl) %>%
map(~lm(mpg~wt, data = .))%>%
sapply(summary)%>%
map_dbl(~.$r.squared)

problem I am facing is:

enter image description here

What is the reason for this. I know I can use lapply or map function here but why can't I use sapply?

CodePudding user response:

You have to use lapply instead of sapply

> mtcars %>%
    split(.$cyl) %>%
    map(~lm(mpg~wt, data = .))%>%
    lapply(summary)%>%
    map_dbl(~.$r.squared)
        4         6         8 
0.5086326 0.4645102 0.4229655

Note that sapply returns a matrix and lapply a list, map_dbl iterates over a list.

Here is another alternative:

> mtcars %>% 
    group_by(cyl) %>% 
    do(models = lm(mpg~wt, data = .)) %>% 
    .$models %>% 
    map_dbl(~summary(.)$r.squared)
[1] 0.5086326 0.4645102 0.4229655

CodePudding user response:

mtcars |> 
    split(mtcars$cyl) |> 
    lapply( \(.x) lm(mpg~wt, data = .x)) |> 
    lapply(summary) |> 
    sapply( `[[`, "r.squared")
     4         6         8 
0.5086326 0.4645102 0.4229655 

Or,

mtcars |> 
    {\(.x) split(.x, .x$cyl)}() |> 
    lapply( \(.x) lm(mpg~wt, data = .x)) |> 
    lapply(summary) |> 
    sapply(`[[`, "r.squared")
     4         6         8 
0.5086326 0.4645102 0.4229655 
  • Related