Weird error with lapply and dplyr/magrittr

☆樱花仙子☆ 提交于 2019-12-11 12:13:19

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/28620893/weird-error-with-lapply-and-dplyr-magrittr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!