本文介绍了列出data.frame的所有因子水平的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

带有 str(data)我得到了的水平(1-2个值)

with str(data) I get the headof the levels (1-2 values)

fac1: Factor w/ 2  levels ... :
fac2: Factor w/ 5  levels ... :
fac3: Factor w/ 20 levels ... :
val: num ...

使用 dplyr :: glimpse(data),我得到了更多的值,但是没有有关因子水平数/值的信息。有没有一种自动的方法来获取data.frame中所有因子变量的所有级别信息?简短格式,其中包含更多信息

with dplyr::glimpse(data) I get more values, but no infos about number/values of factor-levels. Is there an automatic way to get all level informations of all factor vars in a data.frame? A short form with more info for

levels(data$fac1)
levels(data$fac2)
levels(data$fac3)

或更精确地说,是类似

for (n in names(data))
  if (is.factor(data[[n]])) {
    print(n)
    print(levels(data[[n]]))
  }

thx
Christof

thxChristof

推荐答案

以下是一些选择。我们使用 sapply 遍历数据,并获取每一列的级别(假设所有列均 factor class)

Here are some options. We loop through the 'data' with sapply and get the levels of each column (assuming that all the columns are factor class)

sapply(data, levels)

或者如果我们需要管道传输(%>%), ,这可以通过

Or if we need to pipe (%>%) it, this can be done as

library(dplyr)
data %>%
     sapply(levels)

或者另一种选择是 summarise_each dplyr ,我们在 funs 中指定级别

Or another option is summarise_each from dplyr where we specify the levels within the funs.

 data %>%
      summarise_each(funs(list(levels(.))))

这篇关于列出data.frame的所有因子水平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:39