Home > Mobile >  How to convert a 4 rows dataframe to 2*2 matrix in R?
How to convert a 4 rows dataframe to 2*2 matrix in R?

Time:09-16

I have a data frame like this:

name  number
A     287        
B     1390       
C     1595       
D     369

I want to get a numeric data matrix like this:

287  369
1390 1595

with this sequence:

A  D
B  C

which means that A and B are on the left column and D and C are on the right column. The sequence is important. How can I only make the numeric matrix with the sequence that I want? Thank you!

CodePudding user response:

We can sort the 'number' column and create the matrix with matrix

matrix(sort(df1$number), 2, 2,byrow = TRUE)

-output

     [,1] [,2]
[1,]  287  369
[2,] 1390 1595

Or if it needs to be based on the 'name' column

library(dplyr)
library(tidyr)
library(data.table)
df1 %>% 
   mutate(grp = 1   !name %in% c("A", "D"), rn = rowid(grp), 
       name = NULL) %>% 
   pivot_wider(names_from = rn, values_from = number) %>% 
   select(-grp) %>%
   as.matrix

-output

        1    2
[1,]  287  369
[2,] 1390 1595

data

df1 <- structure(list(name = c("A", "B", "C", "D"), number = c(287L, 
1390L, 1595L, 369L)), class = "data.frame", row.names = c(NA, 
-4L))

CodePudding user response:

The following is also an option.

library(dplyr)

df %>%
  filter(name %in% c('A', 'B')) %>%
  bind_cols(filter(df, name %in% c('C', 'D'))) %>%
  select(where(~is.integer(.))) %>%
  as.matrix() %>%
  unname()

#       [,1] [,2]
# [1,]  287 1595
# [2,] 1390  369

Data

df <- structure(list(name = c("A", "B", "C", "D"), number = c(287L, 
1390L, 1595L, 369L)), class = "data.frame", row.names = c(NA, 
-4L))
  • Related