Reputation: 33
I am looking for how to transform a dataframe with combinatorial data and conditions in r.
To be clear, this is my first dataframe :
| x1 A |
| x1 B |
| x1 C |
| x2 A |
| x2 B |
And I would like this :
| x1 A B |
| x1 A C |
| x1 B C |
| x2 A B |
I have started to write code but I am not familiar with the required loops. Indeed, I managed to write the part for one condition(let's say "X1") but I don't know how to create the whole table.
This is where I am :
# 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
Upvotes: 0
Views: 63
Reputation: 25225
Using data.table
and generating combination of 2 elements using combi
:
DT[, transpose(combn(Class, 2L, simplify=FALSE)), by=.(Patent)]
output:
Patent V1 V2
1: x1 A B
2: x1 A C
3: x1 B C
4: x2 A B
data:
library(data.table)
DT <- data.table(Patent=c(rep("x1", 3), rep("x2", 2)), Class=c(LETTERS[1:3], LETTERS[1:2]))
Upvotes: 1