I noticed similar questions were asked but I am having difficulty troubleshooting this function because it is not working. I am trying to create a countif function in r. I have some data about earthquake magnitudes, and I have create data bins (a sequence from 2 to 8 by .1 increments) and I want to see how many earthquakes are greater than or equal to my bin values.
Here is my data, it is earthquake magnitudes. I call this qdta$mag in my function because it is a variable from a greater data frame. I just made this snippet for you all to test.
qdta = sample(seq(0,8,.05),500, replace = T)
Here are my "data bins," the purpose of my function is to count how many earthquakes are greater than or equal to my bin values (2, 2.1, 2.2, 2.3, 2.4, etc). Then, I created the value column to store the counts.
L = as.data.frame(seq(2,8,.1))
L$value = 0
Here is my function - the function runs, like I do not get an error when creating, but it does not run correctly, meaning the count values are not stored.
#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)