Reputation: 23
I want to combine columns with combination results. My data.frame has 4 columns with column name A, B, C and D. I want to merge them and my output will be a vector like c("B_C", "B_D", "C_D").my code is wrong and maybe it could help you, apply function is wrong.
data<-data.frame(A=c(1,2,3), B=c(4,5,6), C=c(7,8,9), D=c(10,11,12))
data
x1<-combinations(c(ncol(data)-1),2, c(2:ncol(data)))
x1
x12<-apply(x1, 1, function(x) paste0(colnames(data)[x1[x,]][1],"_",
colnames(data)[x1[x,]][2])
)
Upvotes: 1
Views: 148
Reputation: 9878
You can use either expand.grid()
or combn()
here
expand.grid
will give you all combinations, and is "order-sensitive", returning both A-B and B-A as unique elements:
library(purrr)
expand.grid(names(data), names(data))%>%pmap_chr(~paste(..., sep = '-'))
[1] "A-A" "B-A" "C-A" "D-A" "A-B" "B-B" "C-B" "D-B" "A-C" "B-C" "C-C" "D-C" "A-D" "B-D" "C-D" "D-D"
combn
will return only the unique combinations, "order-insensitive" - "A-B" and "B-A" are considered the same and one is dropped.:
library(purrr)
data.frame(t(combn(names(data), 2)))%>%pmap_chr(~paste(..., sep = '-'))
[1] "A-B" "A-C" "A-D" "B-C" "B-D" "C-D"
Upvotes: 1
Reputation: 947
I'd go with sapply.
library(gtools)
data<-data.frame(A=c(1,2,3), B=c(4,5,6), C=c(7,8,9) , D=c(10,11,12))
data
x1<-combinations(c(ncol(data)-1),2, c(2:ncol(data)))
x1
[,1] [,2]
[1,] 2 3
[2,] 2 4
[3,] 3 4
x12 <- sapply(1L:nrow(x1), function(x) paste(colnames(data[x1[x,1L:2L]]), collapse = "_"))
x12
[1] "B_C" "B_D" "C_D"
Upvotes: 1