0

I have the following data frame:

A  P(A)
1  0.8
0  0.7
1  0.5
1  0.8
1  0.9
0  0.7
0  0.8

For all 0's in column A, I would like to calculate 1-P(A). This would give me the following dataset:

A  P(A)
1  0.8
0  0.3  ## 1 - 0.7
1  0.5
1  0.8
1  0.9
0  0.3  ## 1 - 0.7
0  0.2  ## 1 - 0.8

I tried this but it doesn't give me the required output.

  for(i in nrow(results)) {
    if(results[i,1]==0) {
      results[i,2]<- 1-results[i,2] 
    }
  }

How is this possible in R?

AngryPanda
  • 1,261
  • 2
  • 19
  • 42
  • Do you want those values as another column in the same data frame? And you want the result of the calculation, right, not an equation for it? – ulfelder Nov 12 '15 at 20:57
  • 1
    Just `df[df$A == 0, 2] <- 1 - df[df$A == 0, 2]` This is very basic operation in R. You really need to read some tutorials. – David Arenburg Nov 12 '15 at 20:58
  • `with(DF, \`P(A)\`^A*(1-\`P(A)\`)^(1-A))` similar to any other programming language... As you can see, `P(A)` is a bad name for a column... There's also `dbinom(DF$A, size=1, prob=DF$\`P(A)\`)` – Frank Nov 12 '15 at 20:59
  • I want it stored in the same column P(A). – AngryPanda Nov 12 '15 at 21:04
  • @DavidArenburg - I'm a Java programmer trying to learn R. – AngryPanda Nov 12 '15 at 21:04

1 Answers1

1
df <- data.frame(A = c(1,0,1,1,1,0,0), P = c(0.8, 0.7, 0.5,0.8, 0.9,0.7,0.8))

df[df$A == 0, "P" ] <- 1 - df[df$A == 0, "P"]
Jacob H
  • 4,317
  • 2
  • 32
  • 39