Question: How to replace number in R
1
gravatar for Kian
12 months ago by
Kian40
Kian40 wrote:

How I can replace number in R 1 to11, 2 to 22 and 0 to 10, also -9 as NA?

         id        rs143        rs148       rs149      rs1490 
 1    02003s         -9          1          2          1    
 2    02003s         -9          0          1          2  
 3    02003s         -9          1          1          2   
 4    02003s         -9          0          1          1
 5    02003s         -9          0          1          1

I want to replace numbers as this format:

         id        rs143        rs148       rs149      rs1490 
 1    02003s         NA          11          22          11    
 2    02003s         NA          10          11          22   
 3    02003s         NA          11          11          22
 4    02003s         NA          10          11          11 
 5    02003s         NA          10          11          11

I tried this

  df[df==1]<-11
  df[df==2]<-22
  df[df==0]<-10

But this error occur:

 In [<-.factor`(`*tmp*`, thisvar, value = 22) :
 invalid factor level, NA generated
number replace R • 1.2k views
ADD COMMENTlink modified 12 months ago by zx87547.1k • written 12 months ago by Kian40

check str of dataframe. I guess some of them are factors instead of integers.

ADD REPLYlink written 12 months ago by cpad011211k

As per cpad0112

Also, this must be connected to your other thread: Separate one column in two column R

ADD REPLYlink modified 12 months ago by zx87547.1k • written 12 months ago by Kevin Blighe41k

Thank you cpda0112 and Dear Kevin for responses, how i can solve this problem!

ADD REPLYlink written 12 months ago by Kian40

can you paste output from str(head(df)), here?

ADD REPLYlink written 12 months ago by cpad011211k
help(as.numeric)
ADD REPLYlink written 12 months ago by Devon Ryan89k
6
gravatar for zx8754
12 months ago by
zx87547.1k
London
zx87547.1k wrote:

As mentioned in the comments some of the columns are class of factor, not numeric. If all SNP columns are numeric, then your existing code should work.

Try below code to convert, factor and numeric columns into numeric:

# lookup for allele recoding
lookup <- setNames(c(NA, 10, 11, 22), c(-9, 0, 1, 2))


res <- cbind(df[, 1, drop = FALSE], 
             data.frame(lapply(df[, -1], function(i) lookup[ as.character(i) ])))

res
#       id rs143 rs148 rs149 rs1490
# 1 02003s    NA    11    22     11
# 2 02003s    NA    10    11     22
# 3 02003s    NA    11    11     22
# 4 02003s    NA    10    11     11
# 5 02003s    NA    10    11     11
ADD COMMENTlink written 12 months ago by zx87547.1k

Thank you zx8754, its RIGHT!

ADD REPLYlink written 12 months ago by Kian40
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 1864 users visited in the last hour