r语言 - 如何从相似数据框架创建相似矩阵?



我在网上找到了这个,并使用它与我的数据:

df <- data.frame(seasons = c("Season1","Season2","Season3","Season4"))
for(i in unique(df$seasons)) {
df[[paste0(i)]] <- ifelse(df$seasons==i,1,0)
}

唯一的挑战是在结果单元格中有一个0,我想从数据帧中填充一个有意义的值,该数据帧的数据排列如下:

3

有三个步骤,决定重建原矩阵,称其为S:

# Make square matrix of zeros
rc <- length(unique(df[[1]]) ) # going to assume that number of unique values is same in both cols
S <- diag(1, rc,rc)
# Label rows and cols
dimnames(S) <- list( sort(unique(df[[1]])), sort( unique(df[[2]])) )
# Assign value to matrix positions based on values of df[[3]]
S[ data.matrix( df[1:2])  ] <-   # using 2 col matrix indexing
df[[3]]
# -------
> S
Season1 Season2 Season3
Season1       1       3       0
Season2       0       1       4
Season3       5       0       1

它现在是一个真正的矩阵,而不是一个数据框架。

最新更新