Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the row names and column names into factor or one of the fields in R?

Tags:

r

How can I turn the following matrix (or table/data frame) with row names & column names,

    A       B
M   27143   18324
F   29522   18875

into something like

27143  M  A
18324  M  B
29522  F  A
18875  F  B

so that I can do some analysis in R?

like image 822
Alby Avatar asked Dec 26 '22 21:12

Alby


1 Answers

You can use the reshape2 package and melt the data.

temp = read.table(header=TRUE, text="    A       B
M   27143   18324
F   29522   18875")
library(reshape2)
temp$id = rownames(temp)
melt(temp)
# Using id as id variables
# id variable value
# 1  M        A 27143
# 2  F        A 29522
# 3  M        B 18324
# 4  F        B 18875
like image 100
A5C1D2H2I1M1N2O1R2T1 Avatar answered Jan 25 '23 23:01

A5C1D2H2I1M1N2O1R2T1