我有一个具有不同列的数据框,这些列是组,这些列的单元格是属于列组的物种.我需要将它转换成一个二进制矩阵,其中列仍然是标题(组),但行将是物种,如果一个物种最初是在该列组中,它将是1,否则将是0.
# Load the dplyr package
library(dplyr)
# Create a list of vectors with different lengths
list_of_vectors <- list(
Z1 = c("E","F","G"),
Z2 = c("A", "B", "C", "D"),
Z3 = c("H","I","J","K","L")
)
# Find the maximum length
max_length <- max(sapply(list_of_vectors, length))
# Pad the vectors with NA to make them the same length
padded_vectors <- lapply(list_of_vectors, function(x) c(x, rep(NA, max_length - length(x))))
# Create the data frame using dplyr
df <- as.data.frame(bind_cols(padded_vectors))
I want to go FROM this:个
# data frame
Z1 Z2 Z3
1 E A H
2 F B I
3 G C J
4 NA D K
5 NA NA L
to this:个
# binary matrix
Z1 Z2 Z3
E 1 0 0
F 1 0 ...
G 1 0
A 0 1
B 0 1
C 0 1
D .. 1
H 0 1
I 1
J ...
K
L
谢谢!