简体   繁体   中英

R data.frame to a matrix like facet_grid

I have a data.frame like this:

toyExample <- matrix(0,6,4)
colnames(toyExample) <- c("a","b","c","value")
rownames(toyExample) <- 1:6

toyExample[,1] <- c(rep(20,4),rep(30,2))
toyExample[,2] <- c(rep(50,4),rep(100,2))
toyExample[,3] <- c(c("Method1","Method2","Method3","Method4","Method3","Method4"))
toyExample[,4] <- 1:6

toyExample <- toyExample %>% as.data.frame()

The data.frame is composed by 6 row and 4 columns. I want to organize my data.frame in a different way. This should be the desiderable result:

whatIwant <- matrix(NA,nrow=2,ncol=4)
rownames(whatIwant) <- c("a=20,b=50","a=30,b=100")
colnames(whatIwant) <- c("Method1","Method2","Method3","Method4")
whatIwant[1,] <- 1:4
whatIwant[2,3:4] <- 5:6 

The row are composed by the combination of two variables, a and b . The columns by the variable c . How I can do it in an automatic way? This is only a toy example, I'd like to do this in a bigger data.frame and it's not possible to do by hand.

Using dplyr and tidyr you can try:

library(dplyr)
library(tidyr)

toyExample %>%
  mutate(a = paste('a =', a), 
         b = paste('b =', b)) %>%
  unite(row, a, b, sep = ',') %>%
  pivot_wider(names_from = c, values_from = value) %>%
  tibble::column_to_rownames('row')

#               Method1 Method2 Method3 Method4
#a = 20,b = 50        1       2       3       4
#a = 30,b = 100    <NA>    <NA>       5       6

We could create the column with glue by interpolating values and then use pivot_wider

library(dplyr)
library(tidyr)
toyExample %>% 
     mutate(new = glue::glue("a = {a}, b = {b}")) %>%
     select(-a, -b) %>%
     pivot_wider(names_from = c, values_from = value) %>% 
     column_to_rownames('new')
#                Method1 Method2 Method3 Method4
#a = 20, b = 50        1       2       3       4
#a = 30, b = 100    <NA>    <NA>       5       6

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