提供以下数据:
M = matrix(c(1,6,"HOME_NET",1,0, 2,6,"OTHER_NET",0,1, 3,7,"OTHER_NET",1,0, 4,7,"HOME_NET",0,1, 5,8,"HOME_NET",1,0),
nrow = 5,
ncol = 5,
byrow = TRUE)
colnames(M) <- c("A_NUMBER", "B_NUMBER", "DESTINATION" , "P1", "P2")
Mdf <- data.frame(M)
我想添加一个额外的列,如果A_NUMBER调用B_NUMBER,其中B_NUMBER的目的地一次是P1中的“OTHER_NET”,P2中是“HOME_NET”,则设置为等于1。例如,对于B_NUMBER = 6,我需要在额外列中看到值1。
我尝试了以下内容:
Mdf$EXTRA <- 0
for (j in 1:nrow(Mdf)){ for (i in 1:nrow(Mdf)){
if(Mdf$B_NUMBER[i] == Mdf$B_NUMBER[j] &&
Mdf$DESTINATION[j] != Mdf$DESTINATION[i]) {
Mdf$EXTRA[j] <- 1 }}}
问题是B_NUMBER = 7,在P1中等于OTHER_NET,在P2中变为HOME_NET,这没关系,因此在额外列中不需要值1。我怎样才能做出这个额外的约束?感谢。
但我想得到这个:
答案 0 :(得分:0)
根据您的说明,如果从EXTRA
转到OTHER_NET
而不是相反,您基本上希望在HOME_NET
列中保留0。实现此目的的一种方法是使用符号(1-0 = 1 Vs 0-1 = -1)。使用dplyr
并将矩阵转换为数据框,
library(dplyr)
df %>%
arrange(B_NUMBER, DESTINATION) %>%
group_by(B_NUMBER) %>%
mutate(EXTRA = as.integer(sum(c(0, diff(P1 - P2)))<0)) %>%
ungroup()
# A tibble: 5 × 6
# A_NUMBER B_NUMBER DESTINATION P1 P2 EXTRA
# <int> <int> <chr> <int> <int> <int>
#1 1 6 HOME_NET 1 0 1
#2 2 6 OTHER_NET 0 1 1
#3 4 7 HOME_NET 0 1 0
#4 3 7 OTHER_NET 1 0 0
#5 5 8 HOME_NET 1 0 0