R语言中函数参数被识别为函数?报错问题求助
Fixing Your R Function & For Loop Errors
Hey there, let's work through these errors you're hitting—they're common syntax mix-ups, so we'll get them sorted quickly!
First: The For Loop Error
Your original code has two key issues that trigger the "could not find function 'value'" error:
- You're using parentheses
()like multiplication, but in R, multiplication requires an asterisk*. Writingvalue(1-value)tells R to treatvalueas a function (which it's not!) instead of multiplyingvalueby(1-value). - Your loop structure is incomplete: you're trying to
return()inside a bare for loop (not inside a function), which won't work as intended, plus you didn't initialize a place to store all thesemvalues you calculate.
Here's the corrected version:
# First, properly define p (adjust the trailing dot if it's intentional in your data) p <- NEQ1data$P.inv # Initialize an empty vector to store results sem_results <- numeric(length(p)) # Loop through each value in p for(i in seq_along(p)){ value <- p[i] sem_results[i] <- sqrt(value * (1 - value) / 10000) } # Now sem_results holds all your calculated standard errors sem_results
Second: The Custom Function Error
Your function has two similar syntax mistakes:
- Again,
a(1-a)is trying to callaas a function—replace that witha * (1 - a). - You're returning
se, but the variable you defined issem(typo!). Also, your parameter callNEQ(1)$P.inv.looks like a typo—should that beNEQ1data$P.inv?
Here's the fixed function and how to use it:
# Corrected function se_fyp <- function(a){ sem <- sqrt(a * (1 - a) / 10000) return(sem) } # Use it with your data (fixing the typo in the data reference) se_results <- se_fyp(NEQ1data$P.inv) se_results
Bonus: Vectorized Alternative (More R-like!)
R is built for vector operations, so you don't even need a for loop or custom function if you don't want to—calculate all standard errors in one line:
sem_vectorized <- sqrt(NEQ1data$P.inv * (1 - NEQ1data$P.inv) / 10000)
This is faster and cleaner than loops for most cases in R!
内容的提问来源于stack exchange,提问作者Rachel Murray-Watson
相关产品推荐
相关产品推荐

