[英]How to apply a custom function between a vector and each the columns of a dataframe?
我想计算 2 个数据帧之间的比例 phi,将第一个数据帧中的一列与第二个数据帧的每一列进行比较。 我只是将矩阵用于示例代码。
mat.1<-matrix(rnorm(30),nrow = 10,ncol = 3)
colnames(mat.1)<-c("A","B","C")
mat.2<-matrix(rnorm(30),nrow = 10,ncol = 3)
colnames(mat.2)<-c("V1","V2","V3")
custom.correlation<-function(x,y){
cor(x,y)
}
我想找到一种以如下方式计算相关性的方法:
cust.corr(A,V1)
cust.corr(A,V2)
cust.corr(A,V3)
cust.corr(B,V1)
等等等等,不使用循环。
我的自定义函数更复杂,直接将 2 个数据帧作为输入。 谢谢
你可以这样做:
name_df <- expand.grid(colnames(mat.1), colnames(mat.2))
f <- function(i) custom.correlation(mat.1[,i[1]], mat.2[,i[2]])
name_df$cor <- apply(name_df, 1, f)
name_df
#> Var1 Var2 cor
#> 1 A V1 0.43061855
#> 2 B V1 -0.24786963
#> 3 C V1 -0.44468358
#> 4 A V2 -0.10678237
#> 5 B V2 0.51727866
#> 6 C V2 0.39317290
#> 7 A V3 -0.31834670
#> 8 B V3 -0.08776827
#> 9 C V3 -0.19823759
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.