[英]How to make the row names and column names into factor or one of the fields in R?
如何使用行名和列名轉換以下矩陣(或表/數據框),
A B
M 27143 18324
F 29522 18875
變成像
27143 M A
18324 M B
29522 F A
18875 F B
這樣我就可以在R中做一些分析?
您可以使用reshape2
包並melt
數據。
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
您還可以使用data.table
將行名添加為第一列,然后根據其行名將其融化
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
或使用gather
代替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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.