merging values horizontally in dataframe

时间:2015-08-07 01:31:30

标签: r

I am trying to merge two subsets of a dataframe together, but neither merge nor cbind seem to do exactly what I want. 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
....

1 个答案:

答案 0 :(得分:2)

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(...) <-.

## 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,

## 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"