首页 > 解决方案 > 如何判断数据框的所有 colSums 或 rowSums(或其他聚合)在 R 中是否相等?

问题描述

我不明白这种行为:

> a = c(1,1,1,1,1)
> (a==1)
[1] TRUE TRUE TRUE TRUE TRUE
> df = data.frame(a=c(1,2,3,4,5), b=c(6,7,8,9,10))
> df
  a  b
1 1  6
2 2  7
3 3  8
4 4  9
5 5 10
> colSums(df)
 a  b 
15 40 
> ndf = apply(df, 2, function(col){col/sum(col)})
> colSums(ndf)
a b 
1 1 
> (colSums(ndf) == 1)
    a     b 
 TRUE FALSE 
> typeof(a)
[1] "double"
> class(a)
[1] "numeric"
> typeof(colSums(ndf))
[1] "double"
> class(colSums(ndf))
[1] "numeric"
> b = c(1,1,1,2,1)
> all(b==1)
[1] FALSE
> (b==1)
[1]  TRUE  TRUE  TRUE FALSE  TRUE
> all(a==1)
[1] TRUE
> all(colSums(ndf)==1)
[1] FALSE

为什么“有效”a和无效的相同测试b不起作用colSums(ndf)

标签: rlistdataframevectorequality

解决方案


推荐阅读