I have a dataset 673 x 232. I want to use for loop to perform Pearson correlation and save p-value and estimate. My code is
vec_lipid <- colnames(df3[,9:232])
df4 <- data.frame(vec_lipid)
df4$p.value <- "0"
df4$estimate <- "0"
for (i in length(vec_lipid)) {
cortest[i] <- cor.test(df3$CSF_Ab42, df3$vec_lipid[i], method = "pearson")
df4[i,2] <- cortest[i]$p.value
df4[i,3] <- cortest[i]$estimate
i = i+1
}
However it doesn't work. Can you please help to adjust the code? Thanks a lot in advance.
If I understood your code correctly, you are only interested in the correlation between columns 9 to 232 and CSF_Ab42. Then you could use following code based on
sapply
, avoiding the use of a loop.The df3 rownames are the corresponding column names of df3, for which the correlation with CSF_Ab42 was computed. If you want to put it inside a column simply add:
df4$lipid <- rownames(df4)
.