【发布时间】:2021-02-23 16:26:46
【问题描述】:
我注意到有人问过类似的问题,但我在排除此功能时遇到了困难,因为它不起作用。我正在尝试在 r 中创建一个 countif 函数。我有一些关于地震震级的数据,我已经创建了数据箱(从 2 到 8 以 0.1 为增量的序列),我想看看有多少地震大于或等于我的箱值。
这是我的数据,是地震震级。我在我的函数中称它为 qdta$mag,因为它是来自更大数据框的变量。我只是做了这个sn-p给大家测试。
qdta = sample(seq(0,8,.05),500, replace = T)
这是我的“数据箱”,我的函数的目的是计算有多少地震大于或等于我的箱值(2、2.1、2.2、2.3、2.4 等)。然后,我创建了 value 列来存储计数。
L = as.data.frame(seq(2,8,.1))
L$value = 0
这是我的函数 - 函数运行,就像我在创建时没有收到错误一样,但它没有正确运行,这意味着未存储计数值。
#creating the number of loops
loop1 = dim(L)[1]
loop2 = dim(qdta)[1]
#creating my function
#1. I want the function to
#A. Look at the z cell of qdta$mag (start with first number)
#then check if its bigger than the first cell in first column of x
# if it is, then add a +1 to the value, if not, leave as is.
#Do this loop however many times I say in loop2 (the size of the qdta),
#then move to the next i (the next bin value in the L dataframe)
countf = function(x){
for(i in loop1){
for(z in loop2){
x[i,2] = ifelse(qdta$mag[z] >= x[i,1],
x[i,2] + 1,
x[i,2])
}
}
}
countf(L)
【问题讨论】:
-
loop2在我运行您的代码时值为 NULL。试试length(Data)而不是Dim。 -
谢谢,我的 loop2 值有效。请注意,在数据示例中,我的数据称为 qdta。供大家参考,我刚刚做了一个新的数据框,叫做Data。
标签: r function nested-loops