I have an R dataframe with one column containing a stringt of numbers but I would like to treat them as a factor (mainly to stop R shortening the numbers using e+04 etc...). One way I have found to fix this problem is to edit the csv file the data is taken from, and add a dummy entry that has a word in the desired column and then reimporting it. How do I get this effect using R functions without messing around with the csv?
To clarify, my dataframe looks like this:
pNum,Condition,numberEntered
1,2,5.0970304e+07
I want to change the data type of numberEntered from numeric to factor and get rid of the pesky e+07.
Method 1: Using scipen option In order to eliminate the exponential notation of the integer, we can use the global setting using options() method, by setting the scipen argument, that is options(scipen = n). Scipen: A penalty to be applied when deciding to print numeric values in fixed or exponential notation.
You can disable scientific notation in the entire R session by using the scipen option. Global options of your R workspace. Use options(scipen = n) to display numbers in scientific format or fixed.
We can use select_if() function to get numeric columns by calling the function with the dataframe name and isnumeric() function that will check for numeric columns.
(1) Right-click a cell where you want to remove scientific notation, and (2) choose Format Cells… 2. In the Format Cells window, (1) select the Number category, (2) set the number of decimal places to 0, and (3) click OK. Now the scientific notation is removed.
As Joshua said, it is a printing issue not a storage issue. You can change the way all numbers are printed (=by adjusting getOption("scipen")
.
x <- c(1, 2, 509703045845, 0.0001)
print(x)
options(scipen = 50)
print(x)
Alternatively, you may wish to change the way just those numbers are formatted. (This converts them to character
.) It is worth getting to know format
and formatC
. To get you started, compare
format(x)
format(x, digits = 10)
format(x, digits = 3)
format(x, digits = 3, scientific = 5)
format(x, trim = TRUE, digits = 3, scientific = 5)
formatC(x)
formatC(x, format = "fg")
formatC(x, format = "fg", flag = "+")
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