user13975917
user13975917

Reputation:

How to change specific values in a dataframe

Could anyone explain how to change the negative values in the below dataframe?

we have been asked to create a data structure to get the below output.

# > df
#   x  y  z
# 1 a -2  3
# 2 b  0  4
# 3 c  2 -5
# 4 d  4  6

Then we have to use control flow operators and/or vectorisation to multiply only the negative values by 10.

I tried so many different ways but cannot get this to work. I get an error when i try to use a loop and because of the letters.

Upvotes: 0

Views: 183

Answers (2)

Sotos
Sotos

Reputation: 51592

Create indices of the negative values and multiply by 10, i.e.

i1 <- which(df < 0, arr.ind = TRUE)
df[i1] <- as.numeric(df[i1]) * 10

#  x   y   z
#1 a -20   3
#2 b   0   4
#3 c   2 -50
#4 d   4   6

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388982

First find out the numeric columns of the dataframe and multiply the negative values by 10.

cols <- sapply(df, is.numeric)
#Multiply negative values by 10 and positive with 1
df[cols] <- df[cols] * ifelse(sign(df[cols]) == -1, 10, 1)
df

#  x   y   z
#1 a -20   3
#2 b   0   4
#3 c   2 -50
#4 d   4   6

Using dplyr -

library(dplyr)

df <- df %>% mutate(across(where(is.numeric), ~. * ifelse(sign(.) == -1, 10, 1)))

Upvotes: 0

Related Questions