简体   繁体   中英

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

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   

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM