Home > database >  Indexing within a dataframe
Indexing within a dataframe

Time:01-24

The task is to multiply all negative numbers by 10 in 'df'.

So I am only able to multiply everything by 10 but when I add an if-statement then everything stops working.

df =

x <- c('a', 'b', 'c', 'd', 'e')
y <- c(-4,-2,0,2,4)
z <- c(3, 4, -5, 6, -8)
# Join the variables to create a data frame

df <- data.frame(x,y,z)
df
##
  x  y  z
1 a -4  3
2 b -2  4
3 c  0 -5
4 d  2  6
5 e  4 -8

my code so far

df2 <- df
df2


for(i in 2:ncol(df2)) {       
  df2[ , i] <- df2[ , i] *10
}
df2

CodePudding user response:

 cbind(df[1], 10^(df[-1] < 0) * df[-1])

  x   y   z
1 a -40   3
2 b -20   4
3 c   0 -50
4 d   2   6
5 e   4 -80

CodePudding user response:

You can achieve this using the dplyr functions mutate and across.

library(dplyr) # install if required

df %>% 
  mutate(across(-x, ~ifelse(. < 0, 10 * ., .)))

This says "for all columns except x, multiple by 10 where the value is < 0, otherwise leave value as is".

Result:

  x   y   z
1 a -40   3
2 b -20   4
3 c   0 -50
4 d   2   6
5 e   4 -80
  •  Tags:  
  • Related