[英]Reading levels of a factor in r
I have a problem reading my variable in R. I have data set like this :我在 R 中读取变量时遇到问题。我有这样的数据集:
Cloumn 1 Cloumn2
Pos S
Pos M
Pos H
Pos S
Neg M
Neg H
Neg S
Neg M
So the first column is a factor of 2 levels, and the second column is a factor of 3 levels.所以第一列是 2 个水平的因子,第二列是 3 个水平的因子。 When I read the file in R it reads the variables as characters and when I assign the second variable to be a factor it gives me a factor of 5 levels , but I have only three levels, can you please help me with this?当我在 R 中读取文件时,它将变量读取为字符,当我将第二个变量指定为一个因子时,它给了我 5 个级别的因子,但我只有三个级别,你能帮我解决这个问题吗?
How are you generating the factors?你是如何产生因子的? If they are being read in as characters, you will need to mutate them into factors with the as_factor()
or as.factor()
.如果它们被作为字符读入,则需要使用as_factor()
或as.factor()
将它们变异为因子。 This gives two levels for the first column and three for the second:这为第一列提供了两个级别,为第二列提供了三个级别:
library(tidyverse)
data <- tribble(~Cloumn1, ~Cloumn2,
"Pos", "S",
"Pos", "M",
"Pos", "H",
"Pos", "S",
"Neg", "M",
"Neg", "H",
"Neg", "S",
"Neg", "M")
data <- data %>%
mutate(across(.cols = everything(), forcats::as_factor))
data$Cloumn1
[1] Pos Pos Pos Pos Neg Neg Neg Neg
Levels: Pos Neg
data$Cloumn2
[1] S M H S M H S M
Levels: S M H
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.