R:将多个特定变量转换为因子
我想从一个更大的数据集中子集10个变量,然后将数据集中的多个特定变量2:10从连续变量转换为因子,同时将变量1保留为连续变量。这就是我所拥有的:R:将多个特定变量转换为因子,r,R,我想从一个更大的数据集中子集10个变量,然后将数据集中的多个特定变量2:10从连续变量转换为因子,同时将变量1保留为连续变量。这就是我所拥有的: data <- read.csv("data.csv") %>% as.tibble() %>% complete() %>% subset("1", "2", "3", "4", "5", &qu
data <- read.csv("data.csv") %>%
as.tibble() %>%
complete() %>%
subset("1", "2", "3", "4", "5", "6", "7", "8", "9", "10") %>%
lapply([,2:10], factor)
我做错了什么?dplyr>=1.0.0
使用新的dplyr::cross:
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将因子应用于2:10列。子集函数将数据和逻辑参数作为参数,但您在括号中提供了一个无效参数,包含多个字符,这与常规R语法不符
你和我在一起可能会很安全
data <- read.csv("data.csv") %>%
as.tibble() %>%
complete() %>%
select(c("2", "3", "4", "5", "6", "7", "8", "9", "10")) %>% as.factor())
将结果重新分配到2:10列
但是,如果看不到您尝试的实际数据和输出,则不确定。您可以在整个系统中使用dplyr
library(dplyr)
#fake data
df <- structure(list(col1 = c(9L, 4L, 7L, 1L, 2L, 5L, 3L, 10L, 6L,
8L), col2 = c(12L, 5L, 12L, 9L, 4L, 11L, 13L, 19L, 10L, 15L),
col3 = c(17L, 14L, 13L, 15L, 14L, 18L, 15L, 23L, 13L, 23L
), col4 = c(18L, 18L, 16L, 21L, 16L, 25L, 20L, 31L, 22L,
33L), col5 = c(22L, 27L, 23L, 27L, 17L, 35L, 28L, 34L, 24L,
38L), col6 = c(32L, 34L, 26L, 29L, 23L, 44L, 29L, 39L, 32L,
42L), col7 = c(38L, 35L, 29L, 37L, 33L, 48L, 31L, 46L, 41L,
47L), col8 = c(42L, 43L, 30L, 46L, 39L, 58L, 34L, 53L, 46L,
49L), col9 = c(48L, 44L, 35L, 54L, 49L, 67L, 41L, 56L, 50L,
51L), col10 = c(54L, 46L, 44L, 57L, 59L, 75L, 45L, 63L, 51L,
56L)), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))
df %>%
select(2:10) %>%
mutate(across(where(is.numeric), as.factor))
请使用dputheaddata至少提供“数据”数据框的一小部分,并将其粘贴在问题的开头。您还应该提供codedplyr mutate的输出:作用域的helpers所有以_if、_at或_all结尾的函数都已被cross取代!谢谢,最新答案。
library(dplyr)
#fake data
df <- structure(list(col1 = c(9L, 4L, 7L, 1L, 2L, 5L, 3L, 10L, 6L,
8L), col2 = c(12L, 5L, 12L, 9L, 4L, 11L, 13L, 19L, 10L, 15L),
col3 = c(17L, 14L, 13L, 15L, 14L, 18L, 15L, 23L, 13L, 23L
), col4 = c(18L, 18L, 16L, 21L, 16L, 25L, 20L, 31L, 22L,
33L), col5 = c(22L, 27L, 23L, 27L, 17L, 35L, 28L, 34L, 24L,
38L), col6 = c(32L, 34L, 26L, 29L, 23L, 44L, 29L, 39L, 32L,
42L), col7 = c(38L, 35L, 29L, 37L, 33L, 48L, 31L, 46L, 41L,
47L), col8 = c(42L, 43L, 30L, 46L, 39L, 58L, 34L, 53L, 46L,
49L), col9 = c(48L, 44L, 35L, 54L, 49L, 67L, 41L, 56L, 50L,
51L), col10 = c(54L, 46L, 44L, 57L, 59L, 75L, 45L, 63L, 51L,
56L)), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))
df %>%
select(2:10) %>%
mutate(across(where(is.numeric), as.factor))