Search code examples
rcharacternumeric

converting text to 1 number in R, and converting NA to )


I'm quite new in R. My question is how can I change all text data in my csv file to 1 number, and changing those are character NA to 0 number.Thanks in advance


Solution

  • Assuming that all data in your CSV file is text, and the NA are represented as text as well, this code should work:

    df <- data.frame(c("hello", "hi", "NA", "hello"), 
                     c("NA", "hi", "NA", "hello"),
                     c("hello", "NA", "NA", "hello"))
    
    
    ifelse(df == "NA", 0, 1)
    

    For example, if you want to change the original CSV, you could use:

    df <- read.csv(filepath)
    df2 <- ifelse(df == "NA", 0, 1)
    write.csv(df2, filepath)
    

    This will NOT work if there is non-text data in your CSV as well.