我正在寻找如何使用r中的组合数据和条件转换数据帧。
要清楚,这是我的第一个数据帧:
| x1 A | | x1 B | | x1 C | | x2 A | | x2 B |
我希望如此:
| x1 A B | | x1 A C | | x1 B C | | x2 A B |
我已经开始编写代码,但我不熟悉所需的循环。实际上,我设法为一个条件编写部分(让我们说“X1”),但我不知道如何创建整个表。
这就是我所在的地方:
# Initiate data frame :
a <- c('x1','A')
b <- c('x1','B')
c <- c('x1','C')
d <- c('x2','D')
matrix <- matrix(c(a,b,c,d),nrow=4,ncol=2,byrow=T)
colnames(matrix) <- c("Patent","Class")
# Combine :
temp <- matrix %>%
filter(Patent == 'x1') %>%
select (Class)
temp <- as.vector(t(temp))
temp2 <- t(combn(temp,2))
temp2
# Associate condition :
vector <- rep("x1",nrow(temp2))
vector
temp3 <- cbind(vector,temp2)
temp3
使用data.table
并使用combi
生成2个元素的组合:
DT[, transpose(combn(Class, 2L, simplify=FALSE)), by=.(Patent)]
输出:
Patent V1 V2
1: x1 A B
2: x1 A C
3: x1 B C
4: x2 A B
数据:
library(data.table)
DT <- data.table(Patent=c(rep("x1", 3), rep("x2", 2)), Class=c(LETTERS[1:3], LETTERS[1:2]))