简体   繁体   中英

Reading levels of a factor in r

I have a problem reading my variable in R. I have data set like this :

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. 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?

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() . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM