Transform positive values into negatives in a data.frame based on a condition in another column (R)

3

I have the following data.frame ::

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

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

I tried this command but it failed:

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
    
asked by anonymous 22.04.2016 / 18:15

2 answers

6

Your code would also work normally, what you were missing was to put the same logical condition inside -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
    
22.04.2016 / 22:50
4

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 which to first filter the rows, 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]
    
22.04.2016 / 18:17