![]() "numeric" "numeric" "numeric" "numeric" "character" "numeric" "numeric" "numeric" "numeric" "factor" Sepal.Length Sepal.Width Petal.Length Petal.Width Species For example the iris dataset: sapply(iris, class) This example can be a quick start: x "character" The most easiest way would be to use unfactor function from package varhandle which can accept a factor vector or even a dataframe: unfactor(your_factor_variable) ![]() However you do the conversion, this operation is unlikely to be the bottleneck in your code, so don't worry too much about it. If the values are mostly unique, there won't be much difference in speed. The speed difference will be most apparent for long vectors with few levels. Why is as.numeric(levels(f)) more efficent than as.numeric(as.character(f))?Īs.numeric(as.character(f)) is effectively as.numeric(levels(f)), so you are performing the conversion to numeric on length(x) values, rather than on nlevels(x) values. Is there a better way to convert a factor to numeric? I have to resort to paste to get the real values: as.numeric(paste(f)) ![]() f <- factor(sample(runif(5), 20, replace = TRUE)) When I convert a factor to a numeric or integer, I get the underlying level codes, not the values as numbers.
0 Comments
Leave a Reply. |