How to check multiple columns for value in R

Hi,

I am beginner in R and want to know how to check single value from data frame ab with multiple columns of data frame bc.

ab <- data.frame(f1 = c("Single","Double","Triangle"),
                 f2 = c("12","15","18"))
bc <- data.frame(f1 = c("Double","Triangle","Square",NA),
                 f2 = c("Square","Double","Triangle","Hexagon"),
                 f3 = c("Single",NA,NA,"Triangle"),
                 f4 = c("Square","Double","Triangle","Multi"),
                 f5 = c("Super","Double","Nano","NA"),
                 f6 = c("Names","Surname","Triangle","NA"))

From dataframe ab, want to check ,if ab$f1 value is in dataframe bc any column [f1:f6] ,if it is there
mutate new column in ab with 1 else 0.

I would like to understand How it works in the for loop.

Thanks in advance.

Can you show what you expect the output would be for this example?


Also, I've added some formatting to the code in your post. In general, you can do the same by adding three backticks before and after your code. So, in the post editing box, you would type:

Blah blah blah

```
x <- 1 + 2
```

Yaddah yaddah

And this would show up as:

Blah blah blah

x <- 1 + 2

Yaddah yaddah

You can read more about it here:

1 Like

Rather than use a for loop, I would make a vector out of bc.

ab <- data.frame(f1 = c("Single","Double","Triangle"),
                 f2 = c("12","15","18"))
bc <- data.frame(f1 = c("Double","Triangle","Square",NA),
                 f2 = c("Square","Double","Triangle","Hexagon"),
                 f3 = c("Single",NA,NA,"Triangle"),
                 f4 = c("Square","Double","Triangle","Multi"),
                 f5 = c("Super","Double","Nano","NA"),
                 f6 = c("Names","Surname","Triangle","NA"))
bcVec <- unlist(bc) #makes a vector from the values in bc

ab$InBC <- as.numeric(ab$f1 %in% bcVec)
ab
#>         f1 f2 InBC
#> 1   Single 12    1
#> 2   Double 15    1
#> 3 Triangle 18    1

Created on 2020-02-13 by the reprex package (v0.2.1)

1 Like

does this new question relate to your previous question ?
It seems structurally quite similar.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.