I am new to R Programming. I wrote a sample program and that returns a value of a particular column in a matrix. When I print the value i get something like this
[1] APPLE
2 Levels : 1 2
How do I get only the value without the levels in the output.
Thanks in advance.
levels provides access to the levels attribute of a variable. The first form returns the value of the levels of its argument and the second sets the attribute.
The droplevels() function in R can be used to drop unused factor levels. This function is particularly useful if we want to drop factor levels that are no longer used due to subsetting a vector or a data frame. where x is an object from which to drop unused factor levels.
The levels() is an inbuilt R function that provides access to the levels attribute. The first form returns the value of the levels of its argument, and the second sets the attribute. You can assign the individual levels using the gl() function.
Most people get confused about levels and characters in R, especially the newbies. The difference is that levels specifically define the factor levels of a factor column and the characters are simple the character column that is not a factor or is not used as a factor but can be converted to a factor.
You can print a factor without displaying the levels by using the max.levels
argument in print()
.
Normal printing:
factor(letters[1:5])
# [1] a b c d e
# Levels: a b c d e
Levels removed:
print(factor(letters[1:5]), max.levels = 0)
# [1] a b c d e
Just to expand on A5C1D2H2I1M1N2O1R2T1's comment, the following command is what prints the variable APPLE
without all that levels stuff:
as.character(APPLE)
To get help on the command within R type:
?as.character
Here is an online R help entry for the command:
https://stat.ethz.ch/R-manual/R-devel/library/base/html/character.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With