具有组合数据和条件的数据框
Dataframe with combinatorial data and conditions
我正在寻找如何使用 r 中的组合数据和条件转换数据框。
需要说明的是,这是我的第一个数据框:
| x1 A |
| x1 B |
| x1 C |
| x2 A |
| x2 B |
我想要这个:
| x1 A B |
| x1 A C |
| x1 B C |
| x2 A B |
我已经开始编写代码,但我不熟悉所需的循环。事实上,我设法为一个条件编写了部分(假设 "X1"),但我不知道如何创建整个 table。
我在这里:
# 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]))
我正在寻找如何使用 r 中的组合数据和条件转换数据框。
需要说明的是,这是我的第一个数据框:
| x1 A |
| x1 B |
| x1 C |
| x2 A |
| x2 B |
我想要这个:
| x1 A B |
| x1 A C |
| x1 B C |
| x2 A B |
我已经开始编写代码,但我不熟悉所需的循环。事实上,我设法为一个条件编写了部分(假设 "X1"),但我不知道如何创建整个 table。
我在这里:
# 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]))