I have some variables var1, var2, ..., var100
I would like to create new variables var1_trun, var2_trun, ..., var100_trun
which should have the same values as var1, var2, ..., var100
except the values above the 90%-percentile. Those values should be set equal to the 90%-percentile of the original vairables.
What is the best way to accomplish this?
I tried:
trun <- function(x) {
assign(paste0(substitute(x),"_trun"))<<-x
assign(paste0(substitute(x),"_trun"))[x>quantile(x, probs=seq(0,1,0.05))[19]]<<-quantile(x, probs=seq(0,1,0.05))[19]
}
trun(data$var1)
I get:
Error in assign(paste0(substitute(x), "_trun")) <<- x :
object 'x' not found.
This is really the wrong approach. Don’t create variables named like this (and, just to clarify: what you actually call them is relatively unimportant; what’s important is that you have data of the same general shape — this data belongs grouped into a homogeneous container). Maintain one variable that’s a list, a vector or a matrix (depending on your data).
This will vastly simplify your code.
That said, your code has a very straightforward error: instead of assign(…) <<- x
, you need to do assign(…, x)
, and specify the target environment. So, in your case:
assign(paste(substitute(x), "trun", sep = "_"), x, envir = parent.frame())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With