I have a data frame where one column has non-numeric values. I need to apply a function on the numeric columns and create new data-frame, but I want to keep the column with non-numeric values in this new data frame.
#Data frame (exemple)
df <- data.frame(col1 = c(1:5), col2 = c(6:10), col3 = c("x","y","z","w","x"))
#Function (example)
sum1 <- function(x){x + 1}
df_aplly <- as.data.frame(apply(df, MARGIN = 2, FUN = sum1))
This example return an error:
Error in x + 1 : non-numeric argument to binary operator
I tried to apply only on the numeric columns:
#Function (exemple)
sum1 <- function(x){x + 1}
df_aplly <- as.data.frame(apply(df[1:2], MARGIN = 2, FUN = sum1))
> df_aplly
col1 col2
1 2 7
2 3 8
3 4 9
4 5 10
5 6 11
It works, but return a new data frame with just 2 columns, but I need to keep the columns non-numeric in this new data frame.
Is there a way to do it using only the 'apply()' function?
#data frame I need:
> df_aplly
col1 col2 df$col3
1 2 7 x
2 3 8 y
3 4 9 z
4 5 10 w
5 6 11 x
You can use dplyr
> df %>%
mutate_if(is.numeric, sum1)
col1 col2 col3
1 2 7 x
2 3 8 y
3 4 9 z
4 5 10 w
5 6 11 x
In base R
> ind <- sapply(df, is.numeric)
> as.data.frame(c(lapply(as.list(df[ind]), sum1), as.list(df[!ind])))
col1 col2 col3
1 2 7 x
2 3 8 y
3 4 9 z
4 5 10 w
5 6 11 x