Nicholas Root
Nicholas Root

Reputation: 555

Weird error with lapply and dplyr/magrittr

Here's a piece of code:

data <- data.frame(a=runif(20),b=runif(20),subject=rep(1:2,10)) %>%
group_by(subject) %>%
do(distance = dist(.))

#no dplyr
intermediate <- lapply(data$distance,as.matrix)
mean.dists <- apply(simplify2array(intermediate),MARGIN = c(1,2),FUN=mean)

#dplyr
mean.dists <- lapply(data$distance,as.matrix) %>%
apply(simplify2array(.),MARGIN=c(1,2),FUN=mean)

Why does the "no dplyr" version work, and the "dplyr" version throws the error, "dim(X) must have a positive length"? They seem identical to me.

Upvotes: 1

Views: 529

Answers (1)

mnel
mnel

Reputation: 115382

The issue is that you haven't quite fully implemented the pipe line. You are using magrittr here, and the issue has little to do with dplyr

data$distance %>% 
   lapply(as.matrix ) %>% 
   simplify2array %>% 
   apply(MARGIN=1:2, FUN=mean)

Upvotes: 3

Related Questions