rnorouzian
rnorouzian

Reputation: 7517

shortening a nested `lapply(sapply())` call in R

My lapply(sapply()) below works just fine. But I was wondering if there is a way to perhaps use just one call to a looping function instead of two like lapply(sapply()) OR a way to make the code shorter?

hsb <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/hsb.csv')
ch <- unique(hsb$sch.id)

ols <- lapply(1:2,function(j)sapply(ch,function(i)coef(lm(math~ses,data=hsb,subset=sch.id==i))[j]))

Upvotes: 0

Views: 89

Answers (2)

AlexB
AlexB

Reputation: 3269

Another way would be to use purrr library:

purrr::map_dfr(ch, ~ coef(lm(math ~ ses, data=hsb, subset=sch.id== .)))

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 389047

You can use a single lapply call instead of fitting the same model twice.

result <- do.call(rbind, lapply(ch,function(i)
                        coef(lm(math~ses,data=hsb,subset=sch.id==i))))

If you want result as a list use asplit :

asplit(result, 2)

Upvotes: 2

Related Questions