r - Converting DF columns to factor is less than straightforward -
this question has answer here:
i'm learning r , welcome explanation/pointers error means , why can't assign columns factors:
in r, read.csv() file variable df. class(df) tells me it's "data.frame" columns 1, 2, , 3 non-factors. when try assign columns 1,2,3 factors error:
asfactors <- c(1:3) df[asfactors] <- as.factors(df[asfactors]) # same if use df[,asfactors] error in sort.list(y) : 'x' must atomic 'sort.list' have called 'sort' on list? what sort have me trying change variable type?
instead, seem need use apply() function convert columns factors (but isn't intuitive thing):
df[,asfactors] <- lapply(df[asfactors], factor) furthermore, if try convert columns 4,5,6 numeric using lapply new error:
asnumeric <- c(4:6) df[,asnumeric] <- lapply(df[asnumeric], numeric) error in fun(x[[i]], ...) : invalid 'length' argument and if fall on original attempt, get:
df[,asnumeric] <- as.numeric(df[,asnumeric]) error: (list) object cannot coerced type 'double' so each variable type seems= need different method of converting columns, or haven't found 1 method applies of them.
to change multiple columns factor, use:
df[,1:3] <- lapply(df[,1:3], factor) to change factor numeric, remember use as.numeric(as.character(x)), this:
df[,1:3] <- lapply(df[,1:3], function(x) as.numeric(as.character(x)))
Comments
Post a Comment