在R

时间:2018-11-19 22:09:53

标签: r dataframe for-loop division

我正在使用一些基本的R函数,并试图创建一个包含数字1:20的余数和商数的表 首先,我创建了此函数:

Find_Remains = function(number, divisor){
              Remainder = number%%divisor
              Quotient = number%/%divisor
              a = c(number, divisor, Remainder, Quotient)
              return(a)
}

我添加一个空白表

final.data.frame = data.frame(matrix(NA, nrow = 1, ncol = 4))

然后我创建了这个for循环

for(i in c(1:20)){
    b[i] = Find_Remains(i,5)
    final.data.frame = rbind(b[i])
}

我得到的错误是:

number of items to replace is not a multiple of replacement length

任何帮助将不胜感激。谢谢

1 个答案:

答案 0 :(得分:0)

初始化final.data.frame的荣誉(尽管我认为最好用20行初始化)。完成不需要使用rbind的操作后,您可以在每次循环运行中简单地替换数据帧的每一行。这就是您需要的-

Find_Remains = function(number, divisor) {
              Remainder = number%%divisor
              Quotient = number%/%divisor
              a = c(number, divisor, Remainder, Quotient)
              return(a)
}

final.data.frame = data.frame(matrix(NA, nrow = 20, ncol = 4))

for(i in 1:20) {
  final.data.frame[i, ] = Find_Remains(i,5)
}

> final.data.frame
   X1 X2 X3 X4
1   1  5  1  0
2   2  5  2  0
3   3  5  3  0
4   4  5  4  0
5   5  5  0  1
6   6  5  1  1
7   7  5  2  1
8   8  5  3  1
9   9  5  4  1
10 10  5  0  2
11 11  5  1  2
12 12  5  2  2
13 13  5  3  2
14 14  5  4  2
15 15  5  0  3
16 16  5  1  3
17 17  5  2  3
18 18  5  3  3
19 19  5  4  3
20 20  5  0  4