Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in R, check if string appears in row of dataframe (in any column)

Tags:

r

temp = structure(list(name1 = structure(c(2L, 1L, 2L, 1L, 2L), .Label = c("Joe", 
"Mike"), class = "factor"), name2 = c("Nick", "Matt", "Nick", 
"Matt", "Nick"), name3 = c("Matt", "Tom", "Tom", "Steve", "Tom"
)), .Names = c("name1", "name2", "name3"), row.names = c(NA, 
-5L), class = "data.frame")

Hi all,

I have what feels like a simple coding question for R. See the following dataframe below, the code for which is above:

  name1 name2 name3
1  Mike  Nick  Matt
2   Joe  Matt   Tom
3  Mike  Nick   Tom
4   Joe  Matt Steve
5  Mike  Nick   Tom

I would like a simple function that returns a boolean vector indicating if a particular name appears in a row (in any column) of this dataframe. For example:

myfunction(Matt) 

# should return
c(TRUE, TRUE, FALSE, TRUE, FALSE).

since Matt appears in the 1st, 2nd and 4th rows. Any simple help with this is appreciated, thanks!

like image 950
Canovice Avatar asked Aug 22 '17 21:08

Canovice


People also ask

How do you check if a row contains a value in R?

You can use the following basic syntax to find the rows of a data frame in R in which a certain value appears in any of the columns: library(dplyr) df %>% filter_all(any_vars(. %in% c('value1', 'value2', ...)))

How do I select a specific row in a value in R?

By using bracket notation on R DataFrame (data.name) we can select rows by column value, by index, by name, by condition e.t.c. You can also use the R base function subset() to get the same results. Besides these, R also provides another function dplyr::filter() to get the rows from the DataFrame. If you have data.

How do I view specific data in R?

There are several ways to check data type in R. We can make use of the “typeof()” function, “class()” function and even the “str()” function to check the data type of an entire dataframe.


1 Answers

Here is an option. Use apply and match (%in%).

apply(temp, 1, function(x) any(x %in% "Matt")) 
[1]  TRUE  TRUE FALSE  TRUE FALSE
like image 113
www Avatar answered Sep 21 '22 06:09

www