0

I have a column Apps in dataframe dframe

that looks like this:

    Apps
1    31
2    12
3    10
4    33
5    -

I need the column to be type int instead of String so I need to convert the 5th row to a 0.

    Apps
1    31
2    12
3    10
4    33
5    0
Paul R
  • 79
  • 2
  • 7
  • 4
    How did you read this data into R? It probably would have been a good idea to use `read.table(..., na.strings="-")` to read it in as missing from the beginning. – MrFlick Dec 14 '18 at 21:23
  • 2
    `dframe$Apps[ dframe$Apps == "-" ] <- "0"`? I agree with MrFlick, though, as a value of "0" is not the same as the hyphen, which many programs (not R) interpret as "not a valid number". I'm guessing that as it is now, it is `character`. Use the `na.strings=` argument, it is very worth it to you to read it in correctly the first time and allow `read.table` to handle the column classes for you. It is not perfect, but anything else suggests something else is wrong with your data. (BTW: `dframe$Apps <- as.numeric(dframe$Apps)` might suffice for you.) – r2evans Dec 14 '18 at 21:25

3 Answers3

3
dframe$Apps[dframe$Apps == "-"] <- "0"
dframe$Apps <- as.integer(dframe$Apps)
Max Ghenis
  • 14,783
  • 16
  • 84
  • 132
0

You can do it with ifelse and the tidyverse approach:

require(tidyverse)

df %>% 
  mutate(Apps = ifelse(Apps == "-", 0, Apps))

  Apps
1    4
2    3
3    2
4    5
5    0

Dataset:

df <- read.table(text = "    Apps
1    31
2    12
3    10
4    33
5    -", header = TRUE)
DJV
  • 4,743
  • 3
  • 19
  • 34
0
dframe$Apps <- as.integer(gsub("-", "0", dframe$Apps, fixed = TRUE))

will give you an integer column as I suspect you want.