Reputation: 2279
I have a data frame made up of vectors that contains factors. I want to add another vector that contains calculation results conditioned to some of the factors:
W | X | Y | Z |
---|---|---|---|
2 | P1 | 15 | if X = P1; Z = Y - W (Result Z = 13) |
2 | P2 | 15 | if X = P2; Z = Y + W (Result Z = 17) |
The attempts I have made have not been successful. Any tips?
w <- seq(2, 20, 2)
x <- c("P1", "P2")
y <- c(15, 30, 45, 60)
data <- expand.grid(W=w, X=x, Y=y)
z_values <- function(X){
if (X == "P1") {
Y - W
} else {
Y + W
}}
data$Z <- z_values(X)
Upvotes: 0
Views: 237
Reputation: 101034
You can try the code below
transform(
data,
Z = Y + W * (1 - 2 * (X == "P1"))
)
or
transform(
data,
Z = Y + W * ifelse(X == "P1", -1, 1)
)
which gives
W X Y Z
1 2 P1 15 13
2 4 P1 15 11
3 6 P1 15 9
4 8 P1 15 7
5 10 P1 15 5
6 12 P1 15 3
7 14 P1 15 1
8 16 P1 15 -1
9 18 P1 15 -3
10 20 P1 15 -5
11 2 P2 15 17
12 4 P2 15 19
13 6 P2 15 21
14 8 P2 15 23
15 10 P2 15 25
16 12 P2 15 27
17 14 P2 15 29
18 16 P2 15 31
19 18 P2 15 33
20 20 P2 15 35
21 2 P1 30 28
22 4 P1 30 26
23 6 P1 30 24
24 8 P1 30 22
25 10 P1 30 20
26 12 P1 30 18
27 14 P1 30 16
28 16 P1 30 14
29 18 P1 30 12
30 20 P1 30 10
31 2 P2 30 32
32 4 P2 30 34
33 6 P2 30 36
34 8 P2 30 38
35 10 P2 30 40
36 12 P2 30 42
37 14 P2 30 44
38 16 P2 30 46
39 18 P2 30 48
40 20 P2 30 50
41 2 P1 45 43
42 4 P1 45 41
43 6 P1 45 39
44 8 P1 45 37
45 10 P1 45 35
46 12 P1 45 33
47 14 P1 45 31
48 16 P1 45 29
49 18 P1 45 27
50 20 P1 45 25
51 2 P2 45 47
52 4 P2 45 49
53 6 P2 45 51
54 8 P2 45 53
55 10 P2 45 55
56 12 P2 45 57
57 14 P2 45 59
58 16 P2 45 61
59 18 P2 45 63
60 20 P2 45 65
61 2 P1 60 58
62 4 P1 60 56
63 6 P1 60 54
64 8 P1 60 52
65 10 P1 60 50
66 12 P1 60 48
67 14 P1 60 46
68 16 P1 60 44
69 18 P1 60 42
70 20 P1 60 40
71 2 P2 60 62
72 4 P2 60 64
73 6 P2 60 66
74 8 P2 60 68
75 10 P2 60 70
76 12 P2 60 72
77 14 P2 60 74
78 16 P2 60 76
79 18 P2 60 78
80 20 P2 60 80
Upvotes: 1