numeric variable a factor and changing to integer changing values in column or NA

I am running a code and data displaying a numeric variable as factor. When changed to character or integer the variable changes values or to to NA. what could be the problem?
below string dataset gives Chlor as factor

str(all)-from data set gives Chlor as factor
'data.frame':	576 obs. of  8 variables:
 $ Block          : int  1 1 1 1 1 1 1 1 1 1 ...
  $ Chlor   : Factor w/ 359 levels "1,5","1,6","1,7",..: 146 271 17 39 269 309 41 79 71 212 ...
 $ LT: Factor w/ 151 levels "20","20,18","21,56",..: 31 25 23 17 19 26 34 17 39 29 ...

changing Chlor to numeric changes values of the column

all$Chlor <- as.numeric(all$Chlor) 
str(allChlrpl) 
 
'data.frame':	576 obs. of  8 variables:
 $ Block          : int  1 1 1 1 1 1 1 1 1 1 ...
  $ Chlor  : num  146 271 17 39 269 309 41 79 71 212 ...
 $ LT: Factor w/ 151 levels "20","20,18","21,56",..: 31 25 23 17 19 26 34 17 39 29 ...

and when the code below is run , Chlor values changes to NA :

all$Chlor <- as.numeric(as.character (all$Chlor))
str(allChlor)

'data.frame':	576 obs. of  8 variables:
 $ Block          : int  1 1 1 1 1 1 1 1 1 1 ...
  $ Chlor    : num  NA NA NA NA NA NA NA NA NA NA ...
 $ LT: Factor w/ 151 levels "20","20,18","21,56",..: 31 25 23 17 19 26 34 17 39 29 ...

If you are in a locale where the decimal separator is a period, you have to replace the commas with periods before running as.numeric.

all <- data.frame(Chlor = c("1,5", "1,6", "1,7"), stringsAsFactors = TRUE)
str(all)
#> 'data.frame':    3 obs. of  1 variable:
#>  $ Chlor: Factor w/ 3 levels "1,5","1,6","1,7": 1 2 3
all$Chlor <- as.character(all$Chlor)
all$Chlor <- sub(",", "\\.", all$Chlor)
str(all)
#> 'data.frame':    3 obs. of  1 variable:
#>  $ Chlor: chr  "1.5" "1.6" "1.7"
all$Chlor <- as.numeric(all$Chlor)
str(all)
#> 'data.frame':    3 obs. of  1 variable:
#>  $ Chlor: num  1.5 1.6 1.7

Created on 2021-07-10 by the reprex package (v0.3.0)

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.