-1
  1. I want to convert some factor variables to numeric variables by this code:

    df$col <- as.numeric(df$col)

  1. The missing values in my dataset are not represented by a dot (i.e., "."). Instead, they are blank cells.

  2. Therefore, the above code allocates a number (i.e., "1") to each blank cells in my dataset.

  3. My question is how I can convert factor variables to numeric ones by replacing blanks cells to NA or changing them to ".".

Thank you so much.

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
ND2020
  • 11
  • 1
  • 2
  • 2
    Please edit your question following these [guidelines](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – NelsonGon Dec 27 '19 at 13:35
  • @jay.sf that question solves part of the problem. There's the blank/NA cells to consider. If you can find a duplicate question that answers coercing from factor and blank cells, we can close it as that. – Roman Luštrik Dec 27 '19 at 13:44
  • @RomanLuštrik That might be not entirely true since these "blank cells" probably also are converted into a factor level. Using the linked answer should yield correctly `NA`. – jay.sf Dec 27 '19 at 13:46

1 Answers1

1

The right way to go about this is to use NA for missing values. In order to convert a factor to numeric, you will have to first coerce to character. But first, replace blank cells with NAs.

x <- factor(c("1", ""))
x[x == ""] <- NA
as.numeric(as.character(x))
[1]  1 NA
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
  • Try `as.numeric(as.character(factor(c("1", ""))))`. – jay.sf Dec 27 '19 at 14:36
  • This code also gave the value 1 to the blank cells. – ND2020 Dec 27 '19 at 18:00
  • @ND2020 did you convert the blank cell to NA before coercing to numeric? If yes, I'd like to see a reproducible example at this point. – Roman Luštrik Dec 28 '19 at 07:20
  • @RomanLuštrik I found a function to address it. The function `unfactor()` converts to character data type first and then converts back to numeric. As a result, blank cells are replaced with NA. – ND2020 Dec 28 '19 at 07:35