[R] Error: level sets of factors are different?

Noia Raindrops noia.raindrops at gmail.com
Fri Aug 17 17:00:19 CEST 2012


The cbind method to data.frame is just a wrapper for data.frame(...). So character columns are converted to factors.

dat <- cbind(data.frame(x = 1:3), a = c("a", "b", "c"), b = c("a", "a", "c"))
str(dat)
## 'data.frame': 3 obs. of  3 variables:
##  $ x: int  1 2 3
##  $ a: Factor w/ 3 levels "a","b","c": 1 2 3
##  $ b: Factor w/ 2 levels "a","c": 1 1 2
dat$a == dat$b
## Error in Ops.factor(dat$a, dat$b) : level sets of factors are different

as.character(dat$a) == as.character(dat$b)
## [1]  TRUE FALSE  TRUE

dat <- cbind(data.frame(x = 1:3), a = c("a", "b", "c"), b = c("a", "a", "c"), stringsAsFactors = FALSE)
str(dat)
## 'data.frame': 3 obs. of  3 variables:
##  $ x: int  1 2 3
##  $ a: chr  "a" "b" "c"
##  $ b: chr  "a" "a" "c"
dat$a == dat$b
## [1]  TRUE FALSE  TRUE

-- 
Noia Raindrops
noia.raindrops at gmail.com




More information about the R-help mailing list