R 如何仅获取唯一的变量组合,其中条目可以位于任一变量中
既然我们有R 如何仅获取唯一的变量组合,其中条目可以位于任一变量中,r,R,既然我们有 j<-c("a","b","c","d") l<-expand.grid(j,j) print(l) Var1 Var2 1 a a 2 b a 3 c a 4 d a 5 a b 6 b b 7 c b 8 d b 9 a c 10 b c 11 c c 12 d c 13 a d 14
j<-c("a","b","c","d")
l<-expand.grid(j,j)
print(l)
Var1 Var2
1 a a
2 b a
3 c a
4 d a
5 a b
6 b b
7 c b
8 d b
9 a c
10 b c
11 c c
12 d c
13 a d
14 b d
15 c d
16 d d
我发现了很多答案,其中变量的独特组合,但变量不会跨越列
所有这些都来自于执行corr.test{psych}和使用as.vector(corr.test$r)将corr.test$r展开为单个向量
为了得到这些相关性是基于我使用的
names<-expand.grid(rownames(corr.test$r),colnames(corr.test$r))
names您可以做的一件事是将答案放入一个数组中,使用Var1作为键,Var2作为值,然后将对添加到临时数组中(如果该对在临时数组中不存在)。您可以做的一件事是将答案放入一个数组中,使用Var1作为键,Var2作为值,然后添加对如果临时数组中不存在该对,则将其放入临时数组。函数将为您提供向量中所有元素的组合,但它不会使元素与其自身匹配。您可以相当容易地添加该结果,因此您可以获得所需的组合
cbind(combn(j,2), rbind(j,j))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# j "a" "a" "a" "b" "b" "c" "a" "b" "c" "d"
# j "b" "c" "d" "c" "d" "d" "a" "b" "c" "d"
combn
函数将为您提供向量中所有元素的组合,但是它不会使元素与其自身匹配。您可以相当容易地添加该结果,因此您可以获得所需的组合
cbind(combn(j,2), rbind(j,j))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# j "a" "a" "a" "b" "b" "c" "a" "b" "c" "d"
# j "b" "c" "d" "c" "d" "d" "a" "b" "c" "d"
您可以重塑数据以避免这种情况
library(psych)
library(reshape2)
# example data
dat <- mtcars[1:4]
# For all correlations
melt(corr.test(dat)$r)
# For unique correlations
out <- corr.test(dat)$r
out[upper.tri(out)] <- NA
melt(out, na.rm=TRUE)
Var1 Var2 value
# 1 mpg mpg 1.0000000
# 2 cyl mpg -0.8521620
# 3 disp mpg -0.8475514
# 4 hp mpg -0.7761684
# 6 cyl cyl 1.0000000
# 7 disp cyl 0.9020329
# 8 hp cyl 0.8324475
# 11 disp disp 1.0000000
# 12 hp disp 0.7909486
# 16 hp hp 1.0000000
图书馆(心理学)
图书馆(E2)
#示例数据
dat您可以重塑数据以避免这种情况
library(psych)
library(reshape2)
# example data
dat <- mtcars[1:4]
# For all correlations
melt(corr.test(dat)$r)
# For unique correlations
out <- corr.test(dat)$r
out[upper.tri(out)] <- NA
melt(out, na.rm=TRUE)
Var1 Var2 value
# 1 mpg mpg 1.0000000
# 2 cyl mpg -0.8521620
# 3 disp mpg -0.8475514
# 4 hp mpg -0.7761684
# 6 cyl cyl 1.0000000
# 7 disp cyl 0.9020329
# 8 hp cyl 0.8324475
# 11 disp disp 1.0000000
# 12 hp disp 0.7909486
# 16 hp hp 1.0000000
图书馆(心理学)
图书馆(E2)
#示例数据
谢谢你的回答
最后我拍了一张照片,下面是我的想法:
j<-c("a","b","c","d")
l<-expand.grid(j,j)
twist<-function(l){
l<-subset(l,l[,1]!=l[,2])
leng<-length(l[,1])/2
for (i in 1:leng) {
g1<-l[,1]
g2<-l[,2]
g1[i]<-l[i,2]
g2[i]<-l[i,1]
l[,1]<-g1
l[,2]<-g2
l<-unique(l[c("Var1", "Var2")])
}
return(l)
}
k<-twist(l)
print(k)
Var1 Var2
2 a b
3 a c
4 a d
7 b c
8 b d
12 c d
j谢谢你的回答
最后我拍了一张照片,下面是我的想法:
j<-c("a","b","c","d")
l<-expand.grid(j,j)
twist<-function(l){
l<-subset(l,l[,1]!=l[,2])
leng<-length(l[,1])/2
for (i in 1:leng) {
g1<-l[,1]
g2<-l[,2]
g1[i]<-l[i,2]
g2[i]<-l[i,1]
l[,1]<-g1
l[,2]<-g2
l<-unique(l[c("Var1", "Var2")])
}
return(l)
}
k<-twist(l)
print(k)
Var1 Var2
2 a b
3 a c
4 a d
7 b c
8 b d
12 c d
j查看expand.grid soln的@Ferdinands答案。查看expand.grid soln.quick note的@Ferdinands答案您可以使用t(combn(j,2))
quick note使用t(combn(j,2))