简体   繁体   English

lapply和dplyr / magrittr的奇怪错误

[英]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"? 为什么“没有dplyr”版本有效,而“dplyr”版本会抛出错误,“dim(X)必须有正长度”? They seem identical to me. 他们看起来和我一模一样。

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 你在这里使用magrittr ,这个问题与dplyr

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM