Home > Enterprise >  R Converting Matrix with Row Names in to a Dataframe where the Row Names are individual variables
R Converting Matrix with Row Names in to a Dataframe where the Row Names are individual variables

Time:01-31

If I have a matrix with row names such as

data<-matrix(1:9, nrow =3, ncol = 3)
fake.names <- c('Abby', 'Bobby', 'Cindy')
rownames(data)<-fake.names
print(data)
    #[,1] [,2] [,3]
    # Abby     1    4    7
    # Bobby    2    5    8
    # Cindy    3    6    9

How can I convert it to a dataframe where the names are variables such as:

# df.names df.numbers
# 1     Abby          1
# 2     Abby          4
# 3     Abby          7
# 4    Bobby          2
# 5    Bobby          5
# 6    Bobby          8
# 7    Cindy          3
# 8    Cindy          6
# 9    Cindy          9

CodePudding user response:

Get the transpose, convert to data.frame and stack it to two column data.frame

stack(as.data.frame(t(data)))[2:1]

-output

     ind values
1  Abby      1
2  Abby      4
3  Abby      7
4 Bobby      2
5 Bobby      5
6 Bobby      8
7 Cindy      3
8 Cindy      6
9 Cindy      9

CodePudding user response:

We can try

data.frame(
  names = row.names(data)[t(row(data))], 
  numbers = c(t(data))
)

which gives

  names numbers
1  Abby       1
2  Abby       4
3  Abby       7
4 Bobby       2
5 Bobby       5
6 Bobby       8
7 Cindy       3
8 Cindy       6
9 Cindy       9

CodePudding user response:

data <- matrix(1:9, nrow = 3, ncol = 3)
fake.names <- c("Abby", "Bobby", "Cindy")
rownames(data) <- fake.names

data.frame(
  df.names = rownames(data),
  df.numbers = c(data)
)
#>   df.names df.numbers
#> 1     Abby          1
#> 2    Bobby          2
#> 3    Cindy          3
#> 4     Abby          4
#> 5    Bobby          5
#> 6    Cindy          6
#> 7     Abby          7
#> 8    Bobby          8
#> 9    Cindy          9

Created on 2022-01-30 by the reprex package (v2.0.1)

  •  Tags:  
  • Related