这是一个 R Base 解决方案
DF <- read.table(text="v1 v2 v3
1 1231 0.1
1 2653 0.3
1 4545 0.4
2 4545 0.6
2 3345 0.1
2 5675 0.7
3 6754 0.2
3 9989 0.85
3 3456 0.4", header=TRUE)
# Correlations and P-values
Result <- sapply(split(DF[,-1], DF$v1), function(x)
c(cor.test(x$v2, x$v3)$estimate, P.val=cor.test(x$v2, x$v3)$p.value))
Result
1 2 3
cor 0.9632826 0.9393458 0.6717314
P.val 0.1730489 0.2228668 0.5311018
如果您想将这些Result
s 添加到原始 data.frame 然后使用transform()
transform(DF,
correlation=rep(Result[1,], table(DF[,1])),
Pval=rep(Result[2,], table(DF[,1])))
v1 v2 v3 correlation Pval
1 1 1231 0.10 0.9632826 0.1730489
2 1 2653 0.30 0.9632826 0.1730489
3 1 4545 0.40 0.9632826 0.1730489
4 2 4545 0.60 0.9393458 0.2228668
5 2 3345 0.10 0.9393458 0.2228668
6 2 5675 0.70 0.9393458 0.2228668
7 3 6754 0.20 0.6717314 0.5311018
8 3 9989 0.85 0.6717314 0.5311018
9 3 3456 0.40 0.6717314 0.5311018