1
votes

I am trying to link my data frame to color by doing this. However, I keep on receiving

"Warning message: In [<-.factor(*tmp*, pca_matrix[, "Subgroup"] == 1, value = c(1L, : invalid factor level, NA generated"

samples_names <- row.names(PCA_Model$rotation)
# Bind sample names to their subgroup
pca_matrix <- cbind(samples_names, "Subgroup"=labeled_subgroup, stringsAsFactors=FALSE)
# Link dataframe to color
pca_matrix[,"Subgroup"][pca_matrix[,"Subgroup"]==1] <- "blue"
pca_matrix[,"Subgroup"][pca_matrix[,"Subgroup"]==2] <- "red"
pca_matrix[,"Subgroup"][pca_matrix[,"Subgroup"]==3] <- "yellow"
pca_matrix[,"Subgroup"][pca_matrix[,"Subgroup"]==4] <- "green"
pca_matrix[,"Subgroup"][pca_matrix[,"Subgroup"]==5] <- "black"
pca_matrix[,"Subgroup"][pca_matrix[,"Subgroup"]==6] <- "white"

I have read other questions online saying it was because my character variable was becoming a factor and I should use the stringsAsFactors = FALSE flag when making your data frame to force "Type" to be a character.

My data frame looks like this and contains subgroups C1 - C6. I want to link the subgroups to a color so I can plot my data as a 3d plot and use the color information to differentiate between groups.

Image

1
The image shows value C1 instead of 1, in 'subgroup', column - akrun

1 Answers

1
votes

Instead of doing this one by one, an option is factor

factor(pca_matrix[,"Subgroup"], levels = paste0("C", 1:6), 
      labels = c("blue", "red", "yellow", "green", "black", "white"))