I know there are lots of questions like this around and tried the solutions proposed. But still I could not solve the following. My aim is to create a function in R which would correlate pairs of columns in data frame. Dependent on the number of pairwise complete observations it would use slightly different approaches. The problem here is no matter what I try, while declaring the function, I keep getting:
Error: no function to return from, jumping to top level
and
Error: unexpected '}' in "}"
Here is the function:
corr.loop <- function(df, varsA, varsB, normal, nonnormal) {
results <- matrix(ncol = 8)
colnames(results) <- c("varA", "varB", "type", "complete.obs.n", "estimate", "p", "lower.CI", "upper.CI")
for (i in 1:length(varsA)) {
for (j in 1:length(varsB)) {
if (
pairwise.complete.obs.n(df[, varsA[i]], df[, varsB[j]]) < 3
) {
results <- rbind(results,
c(
varsA[i],
varsB[j],
NA,
pairwise.complete.obs.n(df[, varsA[i]], df[, varsB[j]]),
rep(NA, 4)
))
} else {
type <- ifelse( (varsA[i] %in% nonnormal | varsB[j] %in% nonnormal), "spearman", "pearson")
cor.results <- ifelse(
type == "pearson",
cor.test(
x = df[, varsA[i]],
y = df[, varsB[j]],
alternative = "two.sided",
method = "pearson",
exact = TRUE,
conf.level = 0.95,
continuity = TRUE
),
cor.test(
x = df[, varsA[i]],
y = df[, varsB[j]],
alternative = "two.sided",
method = "spearman",
exact = TRUE,
conf.level = 0.95,
continuity = TRUE
)
)
if (
pairwise.complete.obs.n(df[, varsA[i]], df[, varsB[j]]) = 3
) {
results <- rbind(
results,
c(
varsA[i],
varsB[j],
type,
pairwise.complete.obs.n(df[, varsA[i]], df[, varsB[j]]),
cor.results$estimate,
cor.results$p.value,
NA,
NA
)
)
} else {
results <- rbind(
results,
c(
varsA[i],
varsB[j],
type,
pairwise.complete.obs.n(df[, varsA[i]], df[, varsB[j]]),
cor.results$estimate,
cor.results$p.value,
cor.results$conf.int[1],
cor.results$conf.int[2]
)
)
}
}
}
}
results <- as.data.frame(results[-1, ])
results[, 1:ncol(results)] <- lapply(results[, 1:ncol(results)], as.character)
results[, 4:ncol(results)] <- lapply(results[, 4:ncol(results)], as.numeric)
return(results)
}
Is there something obvious I am missing? Seems I just need a fresh eye here. Thank you!
Aucun commentaire:
Enregistrer un commentaire