我需要创建一个相关矩阵,但是相关需要在列中的两个变量之间。 例如:
df <- data.frame(
Visit = c(1, 1, 3, 3, 1, 1),
x = c(0, 0.0345, -0.0683, 0.0436, 0.4361, 0.376537),
y = c(0.0181, 0, -0.1765, 0.32656, 0.03516, 0.022662),
z = c(0.0127, 0.3435, -0.04293, 0.0526, 0.351, -0.5732)
)
df
我想在x,y,z等值之间建立关联,但要基于“访问次数”。因此,将每个x,y,z的访问次数相关联(实际上我有〜300 vars),以查看访问次数如何进行比较。
我尝试了见过Run correlation between unequal sized blocks of data in 2 time series和Correlation between two dataframes by row的解决方案
分成两个数据帧,并使用apply函数运行,但是它们的长度不同。
df_1 <- df[(df$Visit=="1"),]
df_2 <- df[(df$Visit=="3"),]
sapply(3:ncol(df_1), function(i) cor(df_1[,i], df_2[,i]))
Error in cor(df_1[, i], df_2[, i]) : incompatible dimensions
'complete.obs'对我没有帮助,因为我需要全部运行它。
cor(df_1$x, df_2$x, method = "pearson", use = "complete.obs")
Error in cor(df_1$x, df_2$x, method = "pearson", use = "complete.obs") :
incompatible dimensions
任何解决方案都很好,因为我想这很简单!
谢谢