首页 > 解决方案 > R:将多个特定变量转换为因子

问题描述

我想从更大的数据集中抽取 10 个变量,然后将数据集中的多个特定变量 (2:10) 从连续变量转换为因子,同时将变量 1 作为连续变量。这就是我所拥有的:

data <- read.csv("data.csv") %>%
  as.tibble() %>%
  complete() %>%
  subset("1", "2", "3", "4", "5", "6", "7", "8", "9", "10") %>%
  lapply([,2:10], factor)

我究竟做错了什么?

标签: r

解决方案


dplyr >= 1.0.0

使用新的dplyr::across

library(dplyr)

data <- read.csv("data.csv") %>%
  as.tibble() %>%
  complete() %>%
  dplyr::mutate(data, across(2:10, factor))

dplyr < 1.0.0

由于 _if, _at, _all 已被取代,这将适用于旧版本,但应使用上述内容。

library(dplyr)

data <- read.csv("data.csv") %>%
  as.tibble() %>%
  complete() %>%
  dplyr::mutate_at(2:10, factor)

mutate_at将应用于factor2:10


推荐阅读