[英]merging values horizontally in dataframe
我正在嘗試將數據幀的兩個子集合並在一起,但是合並和cbind似乎都不能完全滿足我的要求。 到目前為止,我有這個:
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)
我的最終目標是在每個單元格中都這樣:
a b c
a 1/1 -0.6546537/-1 0/-1
....
您可以將兩個矩陣中的條目連接在一起,然后使用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"
另一個技巧是,如果您希望在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.