Home > Back-end >  Changing a matrix from one to another with two row names in R
Changing a matrix from one to another with two row names in R

Time:10-30

I've tried to change from this matrix to another model very hard, but I can't work it out.

Here are some details about my original matrix:

summary(tuPeru1naomit1)
#     Month             YEAR           LAT             LONG            Temp      
# APR    : 73332   Min.   :1980   Min.   :-39.9   Min.   :-89.5   Min.   :10.78  
# AUG    : 73332   1st Qu.:1990   1st Qu.:-31.5   1st Qu.:-86.5   1st Qu.:17.58  
# JUL    : 73332   Median :2000   Median :-23.9   Median :-81.5   Median :19.60  
# JUN    : 73332   Mean   :2000   Mean   :-23.5   Mean   :-81.6   Mean   :19.58  
# MAR    : 73332   3rd Qu.:2011   3rd Qu.:-16.2   3rd Qu.:-77.5   3rd Qu.:21.72  
# MAY    : 73332   Max.   :2021   Max.   : -3.9   Max.   :-70.5   Max.   :29.84  
# (Other):433444                                                                   

   head(tuPeru1naomit)
#  Month YEAR   LAT  LONG    Temp
#1   JAN 1980 -40.0 -89.5 17.5498
#2   JAN 1980 -39.5 -89.5 17.8718
#3   JAN 1980 -39.2 -89.5 18.1983
#4   JAN 1980 -38.9 -89.5 18.5264
#5   JAN 1980 -38.5 -89.5 18.8529
#6   JAN 1980 -38.2 -89.5 19.1596

I'd like to have another matrix like this: Here is my goal matrix

Thanks in advance!.

CodePudding user response:

I think you want something like this. Note that in the example there is only one date, but each date will be its own row in your real data. Also note that I use apply to make the data numeric at the end in order to preserve the col and row names.

library(tidyverse)

#example data
tuPeru1naomit <- read_table("Month YEAR   LAT  LONG    Temp
JAN 1980 -40.0 -89.5 17.5498
JAN 1980 -39.5 -89.5 17.8718
JAN 1980 -39.2 -89.5 18.1983
JAN 1980 -38.9 -89.5 18.5264
JAN 1980 -38.5 -89.5 18.8529
JAN 1980 -38.2 -89.5 19.1596") |>
  as.matrix()

as_tibble(tuPeru1naomit)|>
  unite(date, Month, YEAR, sep = ".")  |>
  pivot_wider(names_from = date, values_from = Temp) |>
  t()  |>
  apply(c(1,2), as.numeric)
#>              [,1]     [,2]     [,3]     [,4]     [,5]     [,6]
#> LAT      -40.0000 -39.5000 -39.2000 -38.9000 -38.5000 -38.2000
#> LONG     -89.5000 -89.5000 -89.5000 -89.5000 -89.5000 -89.5000
#> JAN.1980  17.5498  17.8718  18.1983  18.5264  18.8529  19.1596

CodePudding user response:

I can't see the details of the data (you'd need to provide it, or a reproducible example about the same issue to get more help), but it looks like you just want to transpose it? Try the t() function for that.

  • Related