I'm trying to add the character string "Yam" to row 2 of a column called CropTypeName7 in a dataframe called EnvPerak. The column CropTypeName7 is column number 21. When I go to assign "Yam" using EnvPerak[21,2] <- "Yam"
I get the warning:
Warning message:
In `[<-.factor`(`*tmp*`, iseq, value = "Yam") :
invalid factor level, NA generated
I've read similar questions, with all the answers referring to conversion from a factor to character type column. However, the column was a character column to begin with and I also tried converting to a character type. My full code is below:
> EnvPerak$CropTypeName7 <- as.character(EnvPerak$CropTypeName7)
> str(EnvPerak$CropTypeName7)
chr [1:47] "No additional crops" "No additional crops" "No additional crops" "No additional crops" ...
> View(EnvPerak)
> EnvPerak[21,2] <- "Yam"
Warning message:
In `[<-.factor`(`*tmp*`, iseq, value = "Yam") :
invalid factor level, NA generated
Note, I've tried creating a reproducible example and this works fine? I can't share the full script or code as it is very large and contains unpublished analyses.
name <- rep("No additional crops", 100)
pc <- rep(0, 100)
example <- data.frame(name, pc)
example[21,1] <- "Yam"
CodePudding user response:
You have the row and column indices mixed up. To change the value of CropTypeName7 (column 21) for row number 2, use EnvPerak[2,21] <- "Yam"
or EnvPerak[2,"CropTypeName7"] <- "Yam"
, not EnvPerak[21,2] <- "Yam"
.