Search code examples
rindexingvectorization

Returning positive values in R using only vectorization and indexes


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)))

Solution

  • 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