I'm pretty new to R and in order to better understand the language I'm trying to create a little project.
I have a dataframe with various columns, one of which is called "Size" and contains two possible set of values: a number followed by MB and a number followed by KB. For example
SIZE
32 MB
12 MB
774 KB
I wrote a function that transforms the Size from character to numbers (in Bytes) as follows:
my_f <- function(column) {
return ( as.numeric( gsub( "KB", "e3", gsub( "MB", "e6", column))))
}
The function is invoked by the following piece of code:
df$Size <- my_f(df$Size)
But the code returns this error: In my_f(df$Size) : NAs introduced by coercion
I've tried to modify the function in order to remove unwanted commas, as for my understanding this may be a possible error when transforming to numbers:
my_f <- function(column) {
temp <- gsub(",", "", column)
return ( as.numeric( gsub( "KB", "e3", gsub( "MB", "e6", temp))))
}
But the error still persists.
What am I doing wrong? How can I fix my code?
Thanks in advance!