-3

I have a data as follows.

df <- data.frame(Type=c(1,2,3,4,5), Category1=c(0,1,0,1,0), Category2=c("0.00 %", "1.00 %", "1.00 %", "1.00 %","0.00 %"), Category3=c(0,1,1,0,0),Category4=c("0.00 %", "1.00 %", "1.00 %", "1.00 %","1.00 %"))

I want to only check those rows with 0 and 0.00%.

a <- df[which(df[,2:ncol(df)] == 0),1]
b <- df[which(df[,3:ncol(df)] == sprintf("%.2f %%", 100*0)),1]
intersect(a,b)

It seems 2:ncol(df) is not working.

Expected Result, the return of intersect(a,b) should only be 1.

enter image description here

xiaoni
  • 11
  • 5
  • 1
    Hi xiaoni. Please do not post images of code or data here, but instead please add a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610). That way you can help others to help you! – dario Feb 22 '20 at 07:04
  • @dario I have updated the table example. – xiaoni Feb 22 '20 at 08:01
  • I do not think this code is what you want to be doing, although it is unclear to me what it is exactly that you want. Did you try things like https://stackoverflow.com/questions/43233798/check-if-value-is-in-data-frame/43233981 – Annet Feb 22 '20 at 08:06
  • 1
    Hi xianoni. That example data is unfortunately still of little to no use... Did you look a the link regarding the minimal reproducible example? – dario Feb 22 '20 at 08:08
  • Please share your data with `dput(head(df,n))`. – NelsonGon Feb 22 '20 at 08:19
  • Hi all, I updated the question with the better version. Thank you. – xiaoni Feb 22 '20 at 08:36
  • @Annet I intended to return the whole row that contains the pattern `c(0, 0.00 %, 0, 0.00%, ...)` I don't think %in% is suitable. – xiaoni Feb 22 '20 at 08:47
  • @xiaoni did you even check the answers? As it is not about %in% it is about using all and any, or sum. – Annet Feb 22 '20 at 08:49
  • @xiaoni Please read up on [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and how to give a [minimale reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610) (e.g. don't post images of code or data). Also, at least **try** the suggested answers before dismissing them for no good reason... – dario Feb 22 '20 at 09:06

1 Answers1

0

Using dplyr

apply(df %>% select(-Type), 1, function(r) all(r %in% c(0, sprintf("%.2f %%", 100*0))))

gives you: TRUE FALSE FALSE FALSE FALSE

saving it in a df

df1 <- df %>% 
  mutate(all_zero = apply(df %>% select(-Type), 1, function(r) all(r %in% c(0, sprintf("%.2f %%", 100*0)))))

which gives:

 Type Category1 Category2 Category3 Category4  all_zero
1    1         0    0.00 %         0    0.00 %  TRUE
2    2         1    1.00 %         1    1.00 % FALSE
3    3         0    1.00 %         1    1.00 % FALSE
4    4         1    1.00 %         0    1.00 % FALSE
5    5         0    0.00 %         0    1.00 % FALSE
Annet
  • 846
  • 3
  • 14