how to change value into character in dataframe

Hi,

I would like the letters "AB" to appear in place of 0, " AA" in the place of 1, and BB in place of -1.

SNP <- data.frame(SNP = c(-1,0,1,-1,1,1,0,-1), SNP1 = c(-1,-1,-1,1,-1,0,1,-1), SNP2 = c(0,0,0,1,-1,-1,-1,1))
SNP <- data.frame(SNP = c(-1,0,1,-1,1,1,0,-1),
                  SNP1 = c(-1,-1,-1,1,-1,0,1,-1),
                  SNP2 = c(0,0,0,1,-1,-1,-1,1))

library(tidyverse)

(s2 <- mutate(SNP,
       across(.fns=~factor(.,labels = c("BB","AB","AA")))))
2 Likes

Hi,

Here are two ways of doing this, one in base R, the other one using case_when from dplyr f(Tidyverse, which I prefer)

# Base R
SNP <- data.frame(SNP = c(-1,0,1,-1,1,1,0,-1), 
                  SNP1 = c(-1,-1,-1,1,-1,0,1,-1), 
                  SNP2 = c(0,0,0,1,-1,-1,-1,1))

replace = c("BB", "AB", "AA")

SNP$SNP = replace[SNP$SNP  + 2]
SNP$SNP1 = replace[SNP$SNP1  + 2]
SNP$SNP2 = replace[SNP$SNP2  + 2]

SNP
#>   SNP SNP1 SNP2
#> 1  BB   BB   AB
#> 2  AB   BB   AB
#> 3  AA   BB   AB
#> 4  BB   AA   AA
#> 5  AA   BB   BB
#> 6  AA   AB   BB
#> 7  AB   AA   BB
#> 8  BB   BB   AA


# dplyr - Tidyverse
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
SNP <- data.frame(SNP = c(-1,0,1,-1,1,1,0,-1), 
                  SNP1 = c(-1,-1,-1,1,-1,0,1,-1), 
                  SNP2 = c(0,0,0,1,-1,-1,-1,1))

SNP = SNP %>% mutate(
  across(everything(), function(x){
    case_when(
      x == 0 ~ "AB",
      x == 1 ~ "AA",
      TRUE ~ "BB"
    )
  })
)

SNP
#>   SNP SNP1 SNP2
#> 1  BB   BB   AB
#> 2  AB   BB   AB
#> 3  AA   BB   AB
#> 4  BB   AA   AA
#> 5  AA   BB   BB
#> 6  AA   AB   BB
#> 7  AB   AA   BB
#> 8  BB   BB   AA

Created on 2022-05-20 by the reprex package (v2.0.1)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.