我正在做一个项目,我在 6 周内模拟 8 个课堂社交网络,因此进行了 30 次迭代。学生将根据许多因素相互提名,我计划模拟一些条件,在这些条件下我将其中一些因素删除或添加到模拟中。换句话说,我将重复很多代码,所以我宁愿使用函数而不是尽可能地剪切和粘贴。
现在,我正在尝试创建一个函数,根据他们情绪的相似性来调整一个学生选择另一个学生的概率。当我将它包含在一组嵌套的 for 循环中时,这很好用:
num_students <- 5
names_students <- letters[1:num_students]
student_emotion <- sample(round(runif(5, min = -5, max = 5), digits = 1))
student_emotion_df <- cbind.data.frame(names_students, student_emotion)
probs <- rep(1/num_students, 5)
row_prob <- vector(length = 5)
for(i in 1:num_students){
for(q in 1:num_students){
if(abs(student_emotion[i]-student_emotion[q]) >= 0 &
abs(student_emotion[i]-student_emotion[q]) <= .5){
row_prob[q] <- 1*probs[q]
} else if(abs(student_emotion[i]-student_emotion[q]) > .5 &
abs(student_emotion[i]-student_emotion[q]) <= 1) {
row_prob[q] <- .75 * probs[q]
}
else {
row_prob[q] <- .5 * probs[q]
}
}
}
row_prob 对象是列中学生 i 将在行中选择学生 q 的概率向量。
我已经基于相同的代码创建了一个用户定义的函数,并且有效:
emotion_difference_fun <- function(probs){
for(q in 1:num_students){
if(abs(student_emotion[i]-student_emotion[q]) >= 0 &
abs(student_emotion[i]-student_emotion[q]) <= .5){
row_prob[q] <- 1*probs[q]
} else if(abs(student_emotion[i]-student_emotion[q]) > .5 &
abs(student_emotion[i]-student_emotion[q]) <= 1) {
row_prob[q] <- .75 * probs[q]
}
else {
row_prob[q] <- .5 * probs[q]
}
}
return(row_prob)
}
emotion_difference_fun(probs)
但是,当我尝试将该函数嵌入到遍历列的 for 循环中时,row_prob 作为空向量返回:
for(i in 1:num_students){
emotion_difference_fun(probs)
}
关于如何让它发挥作用的任何想法?
感谢您提供的任何帮助。