简体   繁体   English

在数据框中水平合并值

[英]merging values horizontally in dataframe

I am trying to merge two subsets of a dataframe together, but neither merge nor cbind seem to do exactly what I want. 我正在尝试将数据帧的两个子集合并在一起,但是合并和cbind似乎都不能完全满足我的要求。 So far I have this: 到目前为止,我有这个:

library(psych)
df1<-NULL
df1$a<-c(1,2,3,4,5)
df1$b<-c(4,5,2,6,1)
df1$c<-c(0,9,0,6,3)
df1$gender<-c(0,0,0,1,1)
df1<-as.data.frame(df1)

male<-subset(df1,gender<1)
male<-male[,-c(4)]
female<-subset(df1,gender>=1)
female<-female[,-c(4)]

library(psych)
merge(corr.test(male)$r,corr.test(female)$r)

My end goal is something like this in every cell: 我的最终目标是在每个单元格中都这样:

     a      b                 c
a    1/1    -0.6546537/-1    0/-1
....

You can concatenate the entries in both matrices, then just fix the dimensions of the new vector to be the same as the corr.test output using dim<- , aka dim(...) <- . 您可以将两个矩阵中的条目连接在一起,然后使用dim<- ,又名dim(...) <-将新向量的尺寸固定为与corr.test输出相同。

## Concatenate the entries
strs <- sprintf("%s/%s", round(corr.test(male)$r,2),
                round(corr.test(female)$r, 2))

## Set the dimensions
dim(strs) <- c(3,3)

## Or (to have the value returned at the same time)
`dim<-`(strs, c(3, 3))
#      [,1]       [,2]       [,3]    
# [1,] "1/1"      "-0.65/-1" "0/-1"  
# [2,] "-0.65/-1" "1/1"      "0.76/1"
# [3,] "0/-1"     "0.76/1"   "1/1"   

Another trick, if you want to have those rownames and column names as in the output of corr.test , and not have to worry about dimensions, 另一个技巧是,如果您希望在corr.test的输出中具有这些行名和列名,而不必担心尺寸,

## Get one result
ctest <- corr.test(male)$r

## Concatenate
strs <- sprintf("%s/%s", round(ctest,2),
                round(corr.test(female)$r, 2))

## Overwrite the matrix with the strings
ctest[] <- strs

ctest
#   a          b          c       
# a "1/1"      "-0.65/-1" "0/-1"  
# b "-0.65/-1" "1/1"      "0.76/1"
# c "0/-1"     "0.76/1"   "1/1"   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM