Turn positive values into negative values in a data.frame based on one condition in another column (R)

Asked

Viewed 305 times

4

I have the following date. ::

df <- data.frame(Qtd=c(100,200,300,400,500),
             op=c('V','C','C','V','V'), stringsAsFactors=F)

How I can turn the values in the Qtd column to negative if the op column value is V ??

I tried this command but it was wrong :

Teste <- within(df, Qtd[op == 'V'] <- -Qtd[])

Warning message:
 In Qtd[op == "V"] <- -Qtd[] :
 number of items to replace is not a multiple of replacement length

2 answers

7


Your code would also work normally, what you missed to do was to put the same logical condition within -Qtd[]. Correcting:

within(df, Qtd[op == 'V'] <- -Qtd[op == 'V'])
   Qtd op
1 -100  V
2  200  C
3  300  C
4 -400  V
5 -500  V

5

The ifelse can help you here:

df <- data.frame(Qtd=c(100,200,300,400,500),
                 op=c('V','C','C','V','V'), stringsAsFactors=F)
df$Qtd <- ifelse(df$op == "V", -df$Qtd, df$Qtd)

Or you can also use the which to first filter the lines, and then apply the operation:

df <- data.frame(Qtd=c(100,200,300,400,500),
                 op=c('V','C','C','V','V'), stringsAsFactors=F)
rows <- which(df$op == "V")
df$Qtd[rows] = -df$Qtd[rows]
  • 1

    I think the use of which is redundant, there is no reason to detect the condition indices if the TRUE/FALSE values themselves are sufficient to subseting and change only the V values. The second option can simply be df$Qtd[df$op == "V"] <- -df$Qtd[df$op == "V"]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.