R语言 长型数据与矩阵数据互换
2020-11-11 本文已影响0人
怪毛匠子君
一一对应 转换为 矩阵
tmp <- data.frame(ID1 = c("x","x","y"),
ID2 = c("x","y","x"),
var = c(1,2,3) )
# ID1 ID2 var
#1 x x 1
#2 x y 2
#3 y x 3
library(tidyr)
spread_tmp = spread(tmp, ID2, var)
# ID1 x y
#1 x 1 2
#2 y 3 NA
矩阵转为长条,就是常见的melt了
library(reshape)
melt(spread_tmp,variable_name = "ID2", )
# ID1 ID2 value
#1 x x 1
#2 y x 3
#3 x y 2
#4 y y NA