sam
sam

Reputation: 37

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

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?

Upvotes: 0

Views: 25

Answers (2)

Eyayaw
Eyayaw

Reputation: 1081

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 

Upvotes: 1

Jilber Urbina
Jilber Urbina

Reputation: 61154

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

Upvotes: 1

Related Questions