0

I want to change the class of the column of a data frame so that I can correlate values and create graphs. However, when I use the code below, the values change. The original class of "Depth" is factor and I want to change it to numeric. Could anybody explain to me why this happens and if it is posible to change the class without having this problem?

Original Data frame (Site.copy):

Plot     Depth
1         1.29
2         0.82
3         1.21
4         3.16
5         12.64

Site.copy$Depth<-as.numeric(as.character(Site.copy$Depth))

Changed Site.copy:

Plot     Depth
1         1.290000e+00
2         8.200000e+01
3         1.210000e+00
4         3.160000e+00
5         1.264000e+01
Community
  • 1
  • 1
Cecilia P
  • 29
  • 2
  • try ``as.numeric(as.character)`` Factors can create some problems. – Gainz Jun 27 '19 at 17:17
  • Factors are stored as numbers in r. You could probably do `as.numeric(Site.Copy$Depth))` – yfa Jun 27 '19 at 17:17
  • @yfa that will likely introduce errors, since the numbers of a factor correspond to their *order*, not anything to do with their *value*. See the link in the posted answer – camille Jun 27 '19 at 20:16
  • @camille The author seems to have changed the question a few times. In the original she didn't make clear the class of the column. It seemed, the author changed a character vector to a factor to then make a numeric. I completely agree with the posted answer – yfa Jun 27 '19 at 22:21

1 Answers1

0

try - this has to do with converting factors to numbers

as.numeric(as.character(Site.copy$Depth))

see this explanation: Changing values when converting column type to numeric

R defaults to factors in many cases. You can always check sapply( x , class)

MatthewR
  • 2,660
  • 5
  • 26
  • 37