我想为下面的代码编写一个函数,以避免在长格式代码中重复它们。例如,这些是我的代码:
l = nrow(p)
for (i in 1:l) {
node<- apply(p[c((i + 1) : l), ], 1, function(x){
a = c(as.character(p[i,1]) , as.character(x[1]))
cond1 = ifelse(nrow(Network1[((Network1$from == a[1]) & (Network1$to) == a[2]), ]) != 0 |
nrow(Network1[((Network1$from == a[2]) & (Network1$to) == a[1]), ]) != 0, TRUE, FALSE)
if (((cond1 == 1) & (zsd== 1)) {
return(c(as.character(p[i, 5]), as.character(x[5])))
}
if ((zsd== FALSE)) {
t1 = as.character(p[i, 1]) == as.character(x[1])
mycond = cond1
TT = t1
if (TT + mycond >= z){
return(c(as.character(p[i, 2]), as.character(x[2])))
}
}
})
此代码中已编写1:2数字。但是,我喜欢在函数中收集它们,在这个函数中输入的数字是多少,它生成更多数字的行,如下所示,代码以1:2的形式更改为输入:
l = nrow(p)
for (i in 1:l) {
node<- apply(p[c((i + 1) : l), ], 1, function(x){
a = c(as.character(p[i,1]) , as.character(x[1]))
b = c(as.character(p[i,2]) , as.character(x[2]))
cond1 = ifelse(nrow(Network1[((Network1$from == a[1]) & (Network1$to) == a[2]), ]) != 0 |
nrow(Network1[((Network1$from == a[2]) & (Network1$to) == a[1]), ]) != 0, TRUE, FALSE)
cond2 = ifelse(nrow(Network2[((Network2$from == b[1]) & (Network2$to) == b[2]), ]) != 0 |
nrow(Network2[((Network2$from == b[2]) & (Network2$to) == b[1]), ]) != 0, TRUE, FALSE)
if (((cond1 + cond2 == 1) & (zsd== 1)) |
((cond1 + cond2 == 2) & (zsd== 2)) {
return(c(as.character(p[i, 5]), as.character(x[5])))
}
if ((zsd== FALSE)) {
t1 = as.character(p[i, 1]) == as.character(x[1])
t2 = as.character(p[i, 2]) == as.character(x[2])
mycond = cond1 + cond2
TT = t1 + t2
if (TT + mycond >= z){
return(c(as.character(p[i, 3]), as.character(x[3])))
}
}
})
任何人都知道我该怎么做?或者通过其他方式可以实现这一点吗?我想在我的代码中重复这些行,而不是这些数字。