I have a dataframe with some numeric, some integer and some factor columns. I'm trying to transform the dataframe to square just the numeric columns but the solutions in this thread aren't working in this use case:
square <- function(x){return(x^2)}
Numerics <- function(df){return(Filter(is.numeric,df))}
SquareD <- function(df){
Numerics(df) <- apply(Numerics(df),2,square)
return(df)
}
Now, on trying to run SquareD(iris)
, I get ' Error in Numerics(df) <- apply(Numerics(df), 2, square) : could not find function "Numerics<-" '.
How can I get this to work? Something like
iris[sapply(df,is.numeric)] <- apply(iris[sapply(iris,is.numeric)],2,square)
does actually work but it's long and clunky. I would much rather something short (wrapped in one function) that I could repeat instead. But
Numerics <- function(df){return(df[sapply(df,is.numeric)])}
SquareD <- function(df){
Numerics(df) <- apply(Numerics(df),2,square)
return(df)
}
still doesn't work. Stuff that doesn't use a newly defined function, but is still somewhat short, like
SquareD <- function(df){
Filter(is.numeric,df) <- apply(Filter(is.numeric,df),2,square)
return(df)
}
doesn't work either. (or e.g. dplyr::select_if(df,is.numeric)
in place of Filter(is.numeric,df)
above)
Note: I want to do this as shown above, i.e. with a method that would work for both replacement and selection (hence why I'm trying using the methods for selection suggested in that thread) and is short without having to rewrite somewhat lengthy code (like with the sapply). For example, I might want to replace the numerical columns of ANOTHER dataset with squared values from numerical columns of iris. That kind of application.
I know that for replacement alone I could use dplyr::mutate_if but I don't want that. Rather looking to understand why the select methods don't work here and one can adapt them to. I also want to do it in one line (or with a predefined function that is finally executed in one line) as above. Finally, no libraries but dplyr please.