Search code examples
rdata-analysis

Modify R dataframe character data throw warning and NA generated


I tried to modified dataframe data with character type data, I am getting error and data replaced with NA

# created 3 vectors for data frame
sname <- c("Raj","Hari","Suresh","Ramesh","John")
age <- c(15,17,14,13,18)
city <- c("Chennai","Delhi","Mumbai","Bangalore","Hyderabad")

# created data frame 
student <- data.frame(sname,age,city)

# I tried change age 14 to 10 below statement is working
student[3,2] <- 10 

# When I tried to change Hari to Jeseph, i run below statements
student[2,1] <- "Joseph" 
student[[2,1]] <- "Joseph"

both statements throws warning and NA generated

Warning message:
In `[<-.factor`(`*tmp*`, iseq, value = "Joseph") :
  invalid factor level, NA generated

Solution

  • It's because they're factors. You need to make them strings if you want to manipulate them this way ...

    student <- data.frame(sname, age, city, stringsAsFactors = FALSE)
    
    student[2,1] <- "Joseph"