R语言自定义函数传字符串参数计算平均小费报错的解决方法
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

