How to get this data structure in R?

I am trying to find the Wanted data structure from the current data structure. I partially know the schemas of the expected data structure. The required data structure includes another class list(...)and factor. Current data structure

> print(dat.m)

         [,1] [,2]
ave_max  150   61
ave       60    0
lepo      41    0

dat.m <- structure(c(150L, 60L, 41L, 61L, 0L, 0L), .Dim = c(3L, 2L), .Dimnames = list(
    c("ave_max", "ave", "lepo"), NULL))

Required Data Structure

> print(dat.m)

     Vars    M1    M2 
1 ave_max   150    61 
2 ave        60     0 
3 lepo       41     0 

I know that schematically something close to the following, where the unknowns structure(c(...)androw.names = c(...)

structure(list(Vars = structure(c(...), .Label = c("ave_max", 
"ave", "lepo"), class = "factor"), M1 = c(150, 60, 
41), M2 = c(61, 0, 0)), .Names = c("Vars", "ave_max", "ave", 
"lepo"), class = "data.frame", row.names = c(...))

R: 3.4.0 (backports)
OS: Debian 8.7

0
source share
2 answers

If you do not insist on M1, M2etc. as column names, there is an even shorter solution data.table:

library(data.table)   # CRAN version 1.10.4 used
as.data.table(dat.m, keep.rownames = "Vars")
#      Vars  V1 V2
#1: ave_max 150 61
#2:     ave  60  0
#3:    lepo  41  0

M1, M2 .. , dat.m , :

DT <- as.data.table(dat.m, keep.rownames = "Vars")
setnames(DT, stringr::str_replace(names(DT), "^V(?=\\d+$)", "M"))
DT
#      Vars  M1 M2
#1: ave_max 150 61
#2:     ave  60  0
#3:    lepo  41  0

, , , V , . , Vars, V, V17b, VV3, .


, , , , . , ggplot.

DT_long <- melt(as.data.table(dat.m, keep.rownames = "Vars"), id.vars = "Vars")
DT_long
#      Vars variable value
#1: ave_max       V1   150
#2:     ave       V1    60
#3:    lepo       V1    41
#4: ave_max       V2    61
#5:     ave       V2     0
#6:    lepo       V2     0

, , :

DT_long[, variable := stringr::str_replace(variable, "^V", "M")]
DT_long
#      Vars variable value
#1: ave_max       M1   150
#2:     ave       M1    60
#3:    lepo       M1    41
#4: ave_max       M2    61
#5:     ave       M2     0
#6:    lepo       M2     0

,

dcast(DT_long, Vars ~ ...)
#      Vars  M1 M2
#1:     ave  60  0
#2: ave_max 150 61
#3:    lepo  41  0

, : . .... . ; ... , formula. ( . ?data.table::dcast).

+1

tidyverse

library(tidyverse)
dat.m %>% 
    as.data.frame() %>% 
    rownames_to_column('Vars') %>%
    rename(M1 = V1, M2 = V2)
#     Vars  M1 M2
#1 ave_max 150 61
#2     ave  60  0
#3    lepo  41  0

data.table

library(data.table)
setnames(setDT(as.data.frame(dat.m), keep.rownames = TRUE), c('Vars', 'M1', 'M2'))[]
+1

Source: https://habr.com/ru/post/1017322/


All Articles