You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 *. Writing value(1-value) tells R to treat value as a function (which it's not!) instead of multiplying value by (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 the sem values 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 call a as a function—replace that with a * (1 - a).
  • You're returning se, but the variable you defined is sem (typo!). Also, your parameter call NEQ(1)$P.inv. looks like a typo—should that be NEQ1data$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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:28:38