0

我正在做一个项目,我在 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)
  
}

关于如何让它发挥作用的任何想法?

感谢您提供的任何帮助。

4

2 回答 2

1

如果我正确理解了您的问题,那么您需要在最后一个“for”循环中分配结果:

for(i in 1:num_students){
        if(i == 1) out <- NULL
        out <- c(out, emotion_difference_fun(probs))   
}
out

那是你要找的吗?

不过,我不清楚的是,为什么在您的第二个代码部分中您不是在寻找 5*5 矩阵。最终,在运行该代码时,您为 i = 5 个学生执行此操作并不重要,因为它只会将您的最后一次迭代(学生 = 5)保存在 row_prob 中。

于 2021-02-05T22:13:26.453 回答
0

您可以使用replicate重复该功能emotion_difference_funnum_students

result <- replicate(num_students, emotion_difference_fun(probs))

您还可以设置simplify = FALSE以列表形式获取输出。

result <- replicate(num_students, emotion_difference_fun(probs),simplify = FALSE)
于 2021-02-06T05:46:52.283 回答