开始使用免费开始使用

获取水平数量

dplyr 中,使用 mutate()summarize() 时,您可以借助 across() 来指定:当第一个参数为真时,将它们的第二个参数(一个函数)应用到所有列。

我们将结合使用这些函数和 tidyr,来获取 multiple_choice_responses 中每个因子变量的水平数量。tidyrpivot_longer() 会将数据集从宽格式转换为长格式。它的两个参数是新列名——一个用于存放旧的列名,另一个用于存放所有取值。

本练习是课程的一部分

Tidyverse 中的分类数据

查看课程

练习说明

  • 将所有字符型列转换为因子型列,并将新数据集保存为 responses_as_factors
  • 创建一个新数据集 number_of_levels,其中您需要:
    • 使用 summarize 搭配 across,对每一列应用函数 nlevels()
    • 将数据集从宽格式转换为长格式。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Change all the character columns to factors
responses_as_factors <- multiple_choice_responses %>%
    mutate(___(is.character, as.factor))

number_of_levels <- responses_as_factors %>%
	# Apply the function nlevels to each column
    summarize(___(everything(), ___)) %>%
    # Change the dataset from wide to long
    ___(everything(), names_to = "variable", values_to = "num_levels")
编辑并运行代码