【发布时间】:2020-05-25 11:55:52
【问题描述】:
我有一个数据框,当它们基于有限数量的观察时,我想在其中抑制某些值。
我的数据集如下所示:
> GROUP <- c("A", "B", "C", "D", "E", "F")
> AVERAGE <- c(100, 5, 10, 10, 5, 5)
> N_AVERAGE <- c(53, 5, 12, 20, 50, 2)
> df_average <- data.frame(GROUP , AVERAGE, N_AVERAGE)
> df_average
GROUP AVERAGE N_AVERAGE
1 A 100 53
2 B 5 5
3 C 10 12
4 D 10 20
5 E 5 50
6 F 5 2
我想创建一个新变量 AVERAGE_new,它在“N_AVERAGE”>= 10 时取“AVERAGE”值。当“N_AVERAGE”
这是我的第一次尝试:
funct_suppress <- function(dataset #input dataset
, var_goal # variable to suppress based on other variable
, var_N # variable used to determine whether to suppress
, lower_bound) # lower_bound for var_N, when value is below lower_bound, suppress var_goal
{
dataset <- dataset %>%
mutate(paste0(var_goal,"_new") = ifelse((var_N < lower_bound),NA, var_goal))
}
df_average <- funct_suppress(df_average, AVERAGE, AVERAGE_nw,N_AVERAGE,10) # suppress all AVERAGE when N_AVERAGE < 10
显然,这不起作用。我知道 R 将无法解释 var_goal / var_N 是变量。所以我尝试了以下方法:
> funct_suppress <- function(dataset #input dataset
+ , var_goal # variable to suppress based on other variable
+ , var_goal_nw # suppresses value of var_goal
+ , var_N # variable used to determine whether to suppress
+ , lower_bound) # lower_bound for var_N, when value is below lower_bound, suppress var_goal
+ {
+
+ var_goal= enquo(var_goal)
+ var_goal_nw= enquo(var_goal_nw)
+ var_N = enquo(var_N)
+
+ dataset <- dataset %>%
+ mutate(var_goal = !!var_goal,
+ var_goal_nw = var_goal,
+ var_N = !!var_N,) %>%
+ mutate(var_goal_nw = ifelse((var_N < lower_bound),NA, var_goal)) %>%
+ select(-var_goal, -var_N)
+ }
> df_average <- funct_suppress(df_average, AVERAGE, AVERAGE_nw, N_AVERAGE,10) # suppress all AVERAGE when N_AVERAGE < 10
> df_average
GROUP AVERAGE N_AVERAGE var_goal_nw
1 A 100 53 100
2 B 5 5 NA
3 C 10 12 10
4 D 10 20 10
5 E 5 50 5
6 F 5 2 NA
这确实有效,但我的新变量没有我想要的名称。
我该怎么做?如果一个函数不是解决这个问题的最有效方法,我愿意接受其他建议。 但是,输入变量确实需要能够更改,因为我需要在许多具有不同变量名称的数据帧上执行此任务。
谢谢!
【问题讨论】: