如何比较不同顺序的因子水平?

时间:2019-04-03 07:28:16

标签: r

df <- data.frame(
    cola = c('a','b','c','d','e','e','1',NA,'c','d'),
    colb = c("A",NA,"C","D",'a','b','c','d','c','d'),stringsAsFactors = FALSE)
#equal 2 dataframe
df2<-df

df['cola'] <- lapply(df['cola'], function(x) droplevels(factor(x,levels=c('a','b','c','d','e','f','1'),ordered = FALSE)))

df2['cola'] <- lapply(df2['cola'], function(x) factor(x,ordered = FALSE))

#should be eqaul
dplyr::all_equal(df,df2)

#check levels
levels(df$cola)
levels(df2$cola)

以上脚本的输出为:

> dplyr::all_equal(df,df2)
[1] "Factor levels not equal for column `cola`"

> levels(df$cola)
[1] "a" "b" "c" "d" "e" "1"

> levels(df2$cola)
[1] "1" "a" "b" "c" "d" "e"

对于 ordered = FALSE "a" "b" "c" "d" "e" "1"应等于"1" "a" "b" "c" "d" "e"
为什么all_equal告诉我Factor levels not equal

如何比较这两个因子水平相等?

1 个答案:

答案 0 :(得分:1)

如果您使用原始的all.equal,原因就会更加清楚。

all.equal(df, df2)
# [1] "Component “cola”: Attributes: < Component “levels”: 6 string mismatches >"

您的水平彼此不匹配。简而言之,可以对data.frame的列或两个字符串向量进行补偿:

all.equal(letters[c(3, 1, 2)], letters[c(2, 3, 1)])
# [1] "3 string mismatches"  

您可以改用sort

sort(levels(df$cola)) == sort(levels(df2$cola))
# [1] TRUE TRUE TRUE TRUE TRUE TRUE

要检查所有内容,请使用all

all(sort(levels(df$cola)) == sort(levels(df2$cola)))
# [1] TRUE

您可以将其包装为一个函数。

checkEqualLevels <- function(l, x, y) {
  if (all(sort(levels(x[[l]])) == sort(levels(y[[l]]))))
    cat(paste0("Factor levels are equal for column ", "'", l, "'"))
  else
    cat(paste0("Factor levels not equal for column ", "'", l, "'"))
}
checkEqualLevels("cola", df, df2)
# Factor levels are equal for column 'cola'