Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

apply(temp, 1, function(x) any(x %in% "Matt")) 
[1]  TRUE  TRUE FALSE  TRUE FALSE

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...