Identify correspondence between rows and columns

时间:2017-05-01 15:49:16

标签: r

df <- data.frame("Minute" = c(rep(27, 3), rep(28, 3)),
             "ID" <- c(1,2,3,1,2,3),
             "dist1" = c(0, 1, 4, 2, 4, 1),
             "dist2" = c(1, 0, 0, 0, 1, 0),
             "dist3" = c(0, 0, 2, 1, 4, 0))

At minute 27 ID 1 has a value of 0 with dist3. At minute 27 ID 3 has a value of 4 with dist1. I want to know how to write an "if then" statement or something similar to identify if those values 1) are greater than zero or 2) match. If so, I want to replace the values in this data frame with ones. If not, they become zero.

Expected output for minute 27 only:

df2 <- data.frame("Minute" = c(rep(27, 3)),
             "ID" = c(1,2,3),
             "dist1" = c(0, 1, 0),
             "dist2" = c(1, 0, 0),
             "dist3" = c(0, 0, 0)) 

Another example:

df <- data.frame("Minute" = c(rep(28, 3)),
             "ID" = c(1,2,3),
             "dist1" = c(2, 4, 1),
             "dist2" = c(2, 1, 0),
             "dist3" = c(1, 4, 5))

Expected output:

df2 <- data.frame("Minute" = c(rep(28, 3)),
             "ID" = c(1,2,3),
             "dist1" = c(2, 1, 1),
             "dist2" = c(1, 1, 0),
             "dist3" = c(1, 0, 5))

Notice that ID 1 has a value greater than 0 for dist2 and ID2 has a value greater than 0 for dist1. Those two correspond by being above 0, so I want both of them to become 1.

0 个答案:

没有答案