Home > Back-end >  Returning positive values in R using only vectorization and indexes
Returning positive values in R using only vectorization and indexes

Time:07-10

I have created a data frame which has string and integers. The integers which are positive and negative. I have to change all the ints to be positive without using for/if loops but by only using vectorization and indexing. I have created one with a for loop but I am a bit stuck on the next part.

 df <- data.frame(x = letters[1:5],
                 y = seq(-4,4,2),
                 z = c(3,4,-5,6,-8))

This is my loop to convert to positive.

    loop_df_fn <- function(data){
  for(i in names(data)){
    if(is.numeric(data[[i]])){
      data[[i]][data[[i]]<0] <- abs(data[[i]][data[[i]]< 0])*10
    }
  }
  return(data)
}
print((loop_df_fn(df)))

CodePudding user response:

A tidy solution:

library(dplyr)
df1 <- df %>%
  mutate(across(where(is.numeric), ~if_else(.<0, .*-10, .)))

CodePudding user response:

You can use

df[] <- lapply(df , \(x) if(is.numeric(x)) abs(x)*10 else x)
  • Output
  x y z
1 a 40 30
2 b 20 40
3 c 0  50
4 d 20 60
5 e 40 80

CodePudding user response:

rapply(df, \(x) (x*-10)^(x<0)*x^(x>0), 'numeric', how='replace')
  x  y  z
1 a 40  3
2 b 20  4
3 c  1 50
4 d  2  6
5 e  4 80

rapply(df, \(x) replace(x, x<0, x[x<0]*-10), 'numeric', how='replace')
  x  y  z
1 a 40  3
2 b 20  4
3 c  0 50
4 d  2  6
5 e  4 80

lastly:

ind <- sapply(df, is.numeric)
df[ind][df[ind]<0] <- df[ind][df[ind]<0] * -10
df
  x  y  z
1 a 40  3
2 b 20  4
3 c  0 50
4 d  2  6
5 e  4 80
  • Related