mercredi 21 mars 2018

R: If statement within for loop does not seem to be working?

I have the following dataset(I don't have a high enough reputation so this is the link), and I just want to go through the ID's in the action_ID column and check if is in the 'value' column. If it is, I want to see if the associated variable is a "Comment" or not. If it is a comment, I will add 1 to the count of the number of comments for that ID into a new data frame, called final. Final consists of the action_ID and number of comments.

This is the code I have written so far:

final = data.frame(action_ID = c(1001,981,734,985))

for (x in shares$action_ID) {
    if ((x %in% shares$value) & (shares$variable[shares$value == x] =="Comment")){
      final$num_comments[final$action_ID == x] =+ 1
    }else {
       final$num_comments[final$action_ID == x]  =+ 0
   }
}

Whenever I run it doesn't work. I tried to debug it by just looking at the first condition in the if-statement and it turns out for some reason the if statement isn't really working. Every value in action_ID gets outputted. I also try using any which didn't work either.

for (x in shares$action_ID){
    print(x)
    if (any(shares$value == x)){ # & (shares$variable[shares$value == x]== "Comment")){
        print(x)

    }
}

output:

[1] "734"
[1] "1001"
[1] "1001"
[1] "985"
[1] "981"

Thanks for any help!!

Aucun commentaire:

Enregistrer un commentaire