简体   繁体   中英

How to make the row names and column names into factor or one of the fields in 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?

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

You can also use data.table to add the row names as first column then you melt it based on their row names

df<- structure(list(A = c(27143L, 29522L), B = c(18324L, 18875L)), .Names = c("A", 
"B"), class = "data.frame", row.names = c("M", "F"))

library(data.table)
library(reshape2)
setDT(df, keep.rownames = TRUE)[]

#   rn     A     B
#1:  M 27143 18324
#2:  F 29522 18875

(melt(df, id.vars="rn"))
#   rn variable value
#1:  M        A 27143
#2:  F        A 29522
#3:  M        B 18324
#4:  F        B 18875

Or use gather instead melt

library(tidyr)
gather(df, "rn")
#  rn rn value
#1  M  A 27143
#2  F  A 29522
#3  M  B 18324
#4  F  B 18875

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM