persephone
persephone

Reputation: 420

R stack levels of factor variables into a data frame

How to generate a data frame of stacked levels of a list of factor variables contained in another data frame by some function.


factors <- c("f1", "f2", "f3")

df <- data.frame(f1 = factor(rep(1:3, 10)),
                  f2 = factor(rep(1:2, 15)),
                  f3 = factor(rep(1:3, 10)))

factor_levels <- function(fac = factors, dat = df){

?
}


# In the end, I want something like this:

a b
1 f1
2 f1
3 f1
1 f2
2 f2
1 f3
2 f3
3 f3

Upvotes: 1

Views: 262

Answers (2)

akrun
akrun

Reputation: 886938

We can use stack from base R

out <- stack(lapply(df, as.character))

If the columns are character class or numeric, this is more direct

stack(df)

Upvotes: 0

DaveArmstrong
DaveArmstrong

Reputation: 21757

How about this:

pivot_longer(df, everything(), names_to="b", values_to="a") %>% 
  select(a,b) %>% 
  distinct() %>% 
  arrange(b,a)
# # A tibble: 8 x 2
#    a     b    
#   <fct> <chr>
# 1 1     f1   
# 2 2     f1   
# 3 3     f1   
# 4 1     f2   
# 5 2     f2   
# 6 1     f3   
# 7 2     f3   
# 8 3     f3   

Upvotes: 1

Related Questions