Replace Values in R - Error Received -


i have dataframe, titled gen, data frame made of a's, c's, g's, t's, , 0's. replace 1, c 2, g 3, , t 4. when try using code gen1[gen1 == "a"] = 1, error message:

warning messages: 1: in `[<-.factor`(`*tmp*`, thisvar, value = "1") :   invalid factor level, nas generated 

the resulting data frame has of a's replaced, there na's instead of 1's.

does know how correctly?

thanks

solution:

you can use coerce column factors integer using as.integer:

using sapply:

sapply(gen1,as.integer) 

and colwise plyr:

library(plyr) colwise(as.integer)(gen1) 

for example, generate first data.frame of a,b,c , d:

 set.seed(1) gen1 <- as.data.frame(matrix(sample(letters[1:4], 4 * 5, rep = true), ncol = 4)) ##   v1 v2 v3 v4 ## 1  b  d   b ## 2  b  d   c ## 3  c  c  c  d ## 4  d  c  b  b ## 5    d  d library(plyr) colwise(as.integer)(gen1) ##   v1 v2 v3 v4 ## 1  2  3  1  1 ## 2  2  3  1  2 ## 3  3  2  3  3 ## 4  4  2  2  1 ## 5  1  1  4  3 sapply(gen1, as.integer) ##      v1 v2 v3 v4 ## [1,]  2  3  1  1 ## [2,]  2  3  1  2 ## [3,]  3  2  3  3 ## [4,]  4  2  2  1 ## [5,]  1  1  4  3 

why warning?

the warning messages explicit , invalid factor level, nas generated.

you error because try modify factor value value don't belong levels set, replaced na. reproduce error :

h <- data.frame(xx = factor(c("a","b")) ) h[h == "a"] <- "c"   ## c don't belong levels of xx  warning message: in `[<-.factor`(`*tmp*`, thisvar, value = "c") :   invalid factor level, na generated 

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -