tidyr包replace_na()函数失效及自定义截断正态分布填充函数下标错误求助
Hey there! Let's fix up your function step by step. You've got a couple of syntax issues, some inefficient code, and a problem with how you're handling column references and returning modified data. Here's what's going wrong and how to resolve it:
Key Issues in Your Original Code
- Incorrect
replace_naSyntax: Thereplace_nafunction from dplyr expects a list of column-value pairs (likelist(col = 0)), not a subset assignment likecontinuous_dataset[,col]=0. - Unnecessary Loop: Looping over rows in R is almost never needed—vectorized operations are faster and cleaner.
- Column Reference Error: The error about
colbeing a function type comes from not using tidy evaluation when passing column names. If you pass a bare column name (e.g.,my_colinstead of"my_col"), R doesn't recognize it as a column identifier without proper handling. - Hardcoded Dataset: Your function relies on a global
continuous_datasetvariable, which is bad practice—functions should accept inputs explicitly. - No Return Statement: Your function doesn't return the modified data, so any changes are lost unless you're modifying the global variable (which you shouldn't do).
- Wrong Condition: After replacing NAs with 0, checking
is.na()will never be true—you need to check for 0s instead.
Corrected Function
First, make sure you have the truncnorm package installed and loaded (since rtruncnorm comes from it):
install.packages("truncnorm") library(truncnorm) library(dplyr)
Here's the revised function:
replace_na_with_truncnorm <- function(data, col, min_val, max_val, mean_val, sd_val) { data %>% # Step 1: Replace NA values in the target column with 0 mutate({{ col }} := replace_na({{ col }}, 0)) %>% # Step 2: Replace 0s with truncated normal random numbers mutate({{ col }} := ifelse({{ col }} == 0, round(rtruncnorm(n = n(), a = min_val, b = max_val, mean = mean_val, sd = sd_val)), {{ col }})) }
How to Use It
Call the function by passing your dataset, the bare column name, and your parameters:
# Example usage: continuous_dataset <- replace_na_with_truncnorm( data = continuous_dataset, col = your_column_name, # Replace with your actual column name (bare, no quotes) min_val = 1, max_val = 10, mean_val = 5, sd_val = 2 )
Breakdown of the Fixes
- Tidy Evaluation:
{{ col }}lets you pass bare column names to the function without quotes, which eliminates the subscript error. - Vectorized Operations:
mutateandifelsehandle all rows at once, no need for a loop over 4267 rows. - Explicit Input/Output: The function takes
dataas an argument and returns the modified dataset, so you can assign the result back to your original data (or a new variable). - Correct NA Replacement:
replace_na({{ col }}, 0)properly replaces NAs in the target column with 0. - Correct Condition:
ifelse({{ col }} == 0, ...)replaces only the 0s (originally NAs) with truncated normal values.
Notes
- The
rtruncnormfunction's arguments aren(number of values to generate),a(minimum),b(maximum),mean, andsd—I adjusted the parameter names in the function to match this for clarity. - If you prefer to pass column names as strings (e.g.,
"your_column_name"), you can modify the function to usesym()and!!:
Then call it with quotes:replace_na_with_truncnorm <- function(data, col, min_val, max_val, mean_val, sd_val) { col_sym <- sym(col) data %>% mutate(!!col_sym := replace_na(!!col_sym, 0)) %>% mutate(!!col_sym := ifelse(!!col_sym == 0, round(rtruncnorm(n = n(), a = min_val, b = max_val, mean = mean_val, sd = sd_val)), !!col_sym)) }replace_na_with_truncnorm(continuous_dataset, "your_column_name", ...)
内容的提问来源于stack exchange,提问作者iman j
相关产品推荐
相关产品推荐

