0

I have a dataframe on bat activity with variables

"plot_no" "date" "rec_hour" "guild" "sunrise" "sunriseEnd" "sunsetStart" "sunset" "count" "id"

where ID is a character combination of plot_no, date, rec_hour and guild.

At the moment, if there were no observations for a certain plot_no, date, time and guild, there is no line in the dataframe. I would like to have all relevant combinations of those variables and have a count of zero when there was no observation.

In order to do that, I made a new dataframe with all combinations and all zeros for count. Now I want to add the right count into the zero dataframe using this code:

for (nr in dim(Bat_Data_zeros_)[1]) {
  if (dim(Bat_Data_count[Bat_Data_zeros_$id[nr] == Bat_Data_count$id,])[1]>0) {
    Bat_Data_zeros_$count[nr] <- Bat_Data_count$count[Bat_Data_zeros_$id[nr] == Bat_Data_count$id]
  }
}

but only one value (not even the first one) gets replaced. I checked every part of the code separately to see if it gave the output I was expecting and it all seemed right. I also tried using str_detect (was my first attempt) on the IDs, but the str_detect function for some reason gives back way more matches than there actually are.

4
  • 2
    without sample data it's really difficult to give you a solution. One common suspect is spelling, are you sure your IDs are spelled exactly the same way? (leading / trailing spaces can often cause such issues) Commented Nov 11, 2022 at 9:45
  • Yes, they're spelled the same way, I checked manually by searching some examples in the different dataframes and they always line up. Like I said every separate part of the code seems to work on it's own, but not within the loop. Commented Nov 11, 2022 at 9:49
  • 2
    Why re-invent the wheel when tidyr::complete will do this for you? Commented Nov 11, 2022 at 9:51
  • Obviously bc I didn't know about the function :) thanks for helping, figured it out Commented Nov 11, 2022 at 10:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.