copy factor levels using tidyverse

Hello,
I'm trying to copy the labels from a factor variable using tidyverse.
But I just can't get it.

library(tidyverse)

q=c(1,2,3,3,2,1,1,1,2,1)
z=c(2,2,2,2,2,2,1,1,2,1)

ert<-data.frame(q,z )
asdf<-as_tibble(ert)

asdf %>% 
  mutate(q=as_factor(q)) %>%
  mutate(q=fct_recode(q, 
                      "alfa"="1",
                      "beta"="2",
                      "delta"="3")) 

The code above generates

   q         z
   <fct> <dbl>
 1 alfa      2
 2 beta      2
 3 delta     2
 4 delta     2
 5 beta      2
 6 alfa      2
 7 alfa      1
 8 alfa      1
 9 beta      2
10 alfa      1

But I just want to reproduce something as:

   q         z
   <fct> <fct>
 1 alfa     beta 
 2 beta      beta 
 3 delta     beta 
 4 delta     beta 
 5 beta      beta 
 6 alfa      beta 
 7 alfa      alfa
 8 alfa      alfa
 9 beta      beta 
10 alfa      alfa

Thanks for your time and interest in helping me.

Here is one method.

library(tidyverse)

q=c(1,2,3,3,2,1,1,1,2,1)
z=c(2,2,2,2,2,2,1,1,2,1)

ert<-data.frame(q,z )
asdf<-as_tibble(ert)
FactorFunc <- function(x){
  x <- as_factor(x)
  fct_recode(x, 
             "alfa"="1",
             "beta"="2",
             "delta"="3")
}

asdf %>% map_df(FactorFunc)
#> Warning: Unknown levels in `f`: 3
#> # A tibble: 10 x 2
#>    q     z    
#>    <fct> <fct>
#>  1 alfa  beta 
#>  2 beta  beta 
#>  3 delta beta 
#>  4 delta beta 
#>  5 beta  beta 
#>  6 alfa  beta 
#>  7 alfa  alfa 
#>  8 alfa  alfa 
#>  9 beta  beta 
#> 10 alfa  alfa

Created on 2022-01-03 by the reprex package (v2.0.1)

1 Like
q <- c(1, 2, 3, 3, 2, 1, 1, 1, 2, 1)
z <- c(2, 2, 2, 2, 2, 2, 1, 1, 2, 1)

ert <- data.frame(q, z)
ert$q <- as.factor(ert$q)
ert$z <- as.factor(ert$z)
levs <- c("alpha","beta","delta")
levels(ert$q) <- levs
levels(ert$z) <- levs
str(ert)
#> 'data.frame':    10 obs. of  2 variables:
#>  $ q: Factor w/ 3 levels "alpha","beta",..: 1 2 3 3 2 1 1 1 2 1
#>  $ z: Factor w/ 3 levels "alpha","beta",..: 2 2 2 2 2 2 1 1 2 1
1 Like
asdf %>% 
  mutate(across(c(q,z),~fct_recode(as_factor(.), 
                      "alfa"="1",
                      "beta"="2",
                      "delta"="3")))
1 Like

This topic was automatically closed 21 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.