1

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
1
  • You can cbind your col3 to as.data.frame(apply(df[1:2], MARGIN = 2, FUN = sum1)), i.e. cbind(as.data.frame(apply(df[1:2], 2, sum1)), df$col3) Commented Feb 14, 2024 at 15:21

2 Answers 2

0

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
Sign up to request clarification or add additional context in comments.

Comments

0

You can nest a conditional statement within your function:

sum1 <- function(x){   
     ifelse(!is.na(as.numeric(x)),
     as.numeric(x) + 1,
     x) 
}

Note that you need to coerce x to numeric for this to work, otherwise apply will apparently parse it as character class. Which is odd... but this should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.