group_by,mutate和scale一起出错

时间:2016-01-19 22:46:28

标签: r dplyr

test = data.frame(a=factor(c("A","A","B","B","C","C")),
                  b=c(101,103,50,100,50,60),
                  c=factor(c("John","Mary","John","Mary","John","Mary"))) %>%
  group_by(c) %>% mutate(d=scale(b))
View(test)

为什么在FUN(X [[i]],...)中产生错误错误:   dims [product 3]与对象的长度不匹配[6]

我试图在每个c级别中对b的值进行z分数(即"每个主题")。

2 个答案:

答案 0 :(得分:4)

您在attributes列中收到dR不知道如何查看这些内容。将scale包裹在as.numeric()中会删除这些属性。

library(dplyr)
test = data.frame(a=factor(c("A","A","B","B","C","C")),
                                    b=c(101,103,50,100,50,60),
                                    c=factor(c("John","Mary","John","Mary","John","Mary"))) %>%
    group_by(c) %>% 
    mutate(d = as.numeric(scale(b)))

View(test)

答案 1 :(得分:1)

以下作品:

test = data.frame(a=factor(c("A","A","B","B","C","C")),
               b=c(101,103,50,100,50,60), 
             c=factor(c("John","Mary","John","Mary","John","Mary"))) %>% 
   group_by(c) %>% mutate(d=scale(b)[, 1])
View(test)

这是因为scales返回一个矩阵作为其值,上面的内容是该矩阵的第一列。