Dictionary style replace multiple items

前端 未结 10 607
太阳男子
太阳男子 2020-11-22 05:02

I have a large data.frame of character data that I want to convert based on what is commonly called a dictionary in other languages.

Currently I am going about it li

10条回答
  •  有刺的猬
    2020-11-22 05:32

    Here's something simple that will do the job:

    key <- c('AA','AC','AG')
    val <- c('0101','0102','0103')
    
    lapply(1:3,FUN = function(i){foo[foo == key[i]] <<- val[i]})
    foo
    
     snp1 snp2 snp3
    1 0101 0101 
    2 0103   AT   GG
    3 0101 0103   GG
    4 0101 0101   GC
    

    lapply will output a list in this case that we don't actually care about. You could assign the result to something if you like and then just discard it. I'm iterating over the indices here, but you could just as easily place the key/vals in a list themselves and iterate over them directly. Note the use of global assignment with <<-.

    I tinkered with a way to do this with mapply but my first attempt didn't work, so I switched. I suspect a solution with mapply is possible, though.

提交回复
热议问题