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

R语言自定义函数传字符串参数计算平均小费报错的解决方法

Fixing the "argument is not numeric or logical: returning NA" Error in Your R Function

Hey there! Let's break down why your fun1 function is throwing that error and how to fix it quickly.

The Root Cause

When you use subset(tips, day == x, select = tip), the result is a single-column dataframe, not a numeric vector. The mean() function expects a numeric/logical vector to calculate the average—feeding it a dataframe confuses it, hence the NA error.

Quick Fixes

Here are a few straightforward ways to resolve this:

1. Extract the Column as a Vector (Base R)

Modify your subset call to pull the tip column as a vector using $ or [[ instead of just selecting it in subset:

fun1 <- function(x){
  selectDay <- subset(tips, day == x)$tip  # $ extracts the column as a vector
  cat("Day Selected = ", x, "\n")  # Cat is cleaner for combined print statements
  meanOfDay <- mean(selectDay, na.rm = TRUE)  # Add na.rm to handle missing values
  meanOfDay
}

2. Simplify with Direct Vector Indexing

Skip the intermediate subset step entirely for more concise code:

fun1 <- function(x){
  cat("Day Selected = ", x, "\n")
  mean(tips$tip[tips$day == x], na.rm = TRUE)
}

3. Use Tidyverse (dplyr) for Readability

If you're using the tidyverse ecosystem, this syntax is more intuitive and readable:

library(dplyr)

fun1 <- function(x){
  cat("Day Selected = ", x, "\n")
  tips %>%
    filter(day == x) %>%
    pull(tip) %>%
    mean(na.rm = TRUE)
}

Key Note: Always Handle Missing Values

I added na.rm = TRUE to all examples—this ensures that if there are any NA values in your tip column, the function will still return a valid average instead of NA.

Testing fun1("Sun") now should give you the correct average tip for Sunday!

内容的提问来源于stack exchange,提问作者koreankiwitea

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:21:43