I would like to choose rows based on the subsets of their names, for example
If I have the following data:
data <- structure(c(91, 92, 108, 104, 87, 91, 91, 97, 81, 98), .Names = c("fee-", "fi", "fo-", "fum-", "foo-", "foo1234-", "123foo-", "fum-", "fum-", "fum-"))
how do I select the rows matching 'foo'?
using grep() doesn't work:
grep('foo', data)
returns:
integer(0)
what am I doing wrong? or, is there a better way?
Thanks!
grep() function in R Language is used to search for matches of a pattern within each element of the given string. Parameters: pattern: Specified pattern which is going to be matched with given elements of the string.
The grep command can search for a string in groups of files. When it finds a pattern that matches in more than one file, it prints the name of the file, followed by a colon, then the line matching the pattern.
Introduction. grep is a utility for searching text for lines that match a regular expression. The name stands for: globally search for a regular expression and print matching lines.
You need to grep the names property of data, not the values property.
For your example, use
> grep("foo",names(data)) [1] 5 6 7 > data[grep("foo",names(data))] foo- foo1234- 123foo- 87 91 91
One other clean way to do this is using data frames.
> data <- data.frame(values=c(91, 92, 108, 104, 87, 91, 91, 97, 81, 98), names = c("fee-", "fi", "fo-", "fum-", "foo-", "foo1234-", "123foo-", "fum-", "fum-", "fum-")) > data$values[grep("foo",data$names)] [1] 87 91 91
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