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!
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', ...)))
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.
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.
Here is an option. Use apply
and match (%in%
).
apply(temp, 1, function(x) any(x %in% "Matt"))
[1] TRUE TRUE FALSE TRUE FALSE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With