convert one factor to another in R -
i have dataframe
division | category | tools | work b | tools b | tools
both columns factor variables. how convert tools tools?
i tried
df$category <- as.character(df$category) df$category <- lapply(df$category, function(x) { tolower(x) } ) df$category <- as.factor(df$category)
but last command get:
error in sort.list(y) : 'x' must atomic 'sort.list' have called 'sort' on list?
what mean?
the error means you've tried factor list, although not in words. triggered because used lapply()
, returns list. , in situation as.factor()
calls factor()
, in turn calls sort.list()
here:
## factor() if (missing(levels)) { y <- unique(x, nmax = nmax) ind <- sort.list(y) ... }
which error occurs.
as.factor(list(1, 2)) # error in sort.list(y) : 'x' must atomic 'sort.list' # have called 'sort' on list?
long story short, can use tolower()
without lapply()
, vectorized , character coercion you.
df$category <- factor(tolower(df$category)) df # division category # 1 tools # 2 work # 3 b tools # 4 b tools
Comments
Post a Comment