Changing Class of Data Columns

Hi! I'm very new to R and keep running into an issue with changing the class of my data columns. I watched and read some tutorials which led me to the code

my_data_inflow %>% **
** mutate( Depth = as.numeric(Depth..m.))

for example. However, when I then use

sapply(my_data_inflow, class)

I see that the Depth column is still character, not numeric. Does anyone have any suggestions for this? Thank you so much in advance!

Hi!

To help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

Hi! Thanks for the reprex guide! I tried my best to create one so I hope that this is helpful! Using the iris data set and the tidyverse package, let's say I wanted to change the class of the Sepal.Length column from numeric to character (in my case I want to change something from character to numeric, but I think the process is similar). This is the code I tried based on some research:

library(tidyverse)
iris %>%
mutate( Sepal.Length = as.character(Sepal.Length)) %>%
sapply(iris, class)

This gives an error message. I don't get the error message with my own data set, but the class conversion simply doesn't occur haha. Do you by chance know of a better way to convert the class of a data column? Thank you!

Most R functions don't perform in-place modifications, if you want the changes to persist, you have to explicitly assign them to a variable

library(tidyverse)

iris <- iris %>%
    mutate( Sepal.Length = as.character(Sepal.Length))

sapply(iris, class)
#> Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
#>  "character"    "numeric"    "numeric"    "numeric"     "factor"

Created on 2021-01-03 by the reprex package (v0.3.0.9001)

1 Like

Ohh that makes sense, thanks! So then is it necessary to always store any changes I make into my variable? Sorry if this is a simple question I wasn't aware I needed to do that!

Yes, all changes generate a new object, you have to explicitly assign it to an existing or new object if you want them to persist.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.