Home > Software engineering >  How to make a custom function that modifies a specific column in df (by using $ dollar indexing)
How to make a custom function that modifies a specific column in df (by using $ dollar indexing)

Time:11-18

input dataframe (named df)

v1 v2 v3 #header
a_1 a_2 a_3
b_1 b_2 b_3

output

v1 v2 v3
a1 a2 a3
b1 b2 b3

I make custom function

my_fun <- function(x){
x<<-gsub("_","",x)}

but.. it is impossible

my_fun(df$v1)
my_fun(df$v2)

df does not change.

What's the problem with my code? Is there a good way to make a user-defined function?

CodePudding user response:

On re-reading your post, I think @Aurele is right in that this is a more fundamental misunderstanding on how to store function output in a (new) R object.


You need to loop through the columns of your data.frame

df[] <- lapply(df, my_fun)
df
#  v1 v2 v3
#1 a1 a2 a3
#2 b1 b2 b3

Or vectorise your function.

my_fun_vec <- Vectorize(my_fun)
my_fun_vec(df)
#     v1   v2   v3  
#[1,] "a1" "a2" "a3"
#[2,] "b1" "b2" "b3"

Note that the latter returns a matrix rather than a data.frame. To recast as a data.frame you can do as.data.frame(my_fun_vec(df)).

  •  Tags:  
  • r
  • Related