Add values to dataframe when condition met in R -
i have dataframe this:
id1 id2 position grade day 234 756 2 87 27 245 486 4 66 26 321 275 1 54 20 768 656 6 51 7 421 181 1 90 14 237 952 8 68 23 237 553 4 32 30
and have dataframe this:
id1 id2 day count 234 756 2 3 245 486 2 1 209 706 2 1 124 554 2 2 237 553 2 4
i need add counts first dataframe id1, id2 , day matched. however, need have if there no match (no counts in second dataframe set of id1, id2 , day in first dataframe) 0 put in place. final dataframe like:
id1 id2 position grade day count 234 756 2 87 27 3 245 486 4 66 26 1 321 275 1 54 20 0 768 656 6 51 7 0 421 181 1 90 14 0 237 952 8 68 23 0 237 553 4 32 30 4
this can useful
> # first, merge df1 , df2 > df3 <- merge(df1, df2, by=c("id1", "id2"), all.x=true) > # replace na 0's > transform(df3[, -6], count=ifelse(is.na(count), 0, count)) id1 id2 position grade day.x count 1 234 756 2 87 27 3 2 237 553 4 32 30 4 3 237 952 8 68 23 0 4 245 486 4 66 26 1 5 321 275 1 54 20 0 6 421 181 1 90 14 0 7 768 656 6 51 7 0
Comments
Post a Comment