-1

Basically I'm tasked with making a simple phonebook in R.

I've made a large array which each entry following this pattern (FirstName LastName PhoneNumber, FirstName LastName PhoneNumber, etc.)

I need to do a simple print of someones info, like say first name was John it would return me all indexes starting with john.

I know I need an if statement but I do not know the proper syntax that I could just identify the beginning of the string. Can anyone help me?

CPP Noob
  • 11
  • 1
  • 3

4 Answers4

0
x <- c('Mary Higgins', 'John Williams', 'Zhu Wang', 'Peter Johnson')
# all elements containing John
grep('John', x)
#[1] 2 4
# starting with John
grep('^John', x)
#[1] 2
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
0

From this question: Test if characters in string in R

chars <- "test"
value <- "es"

grepl(value, chars)
SeldomSeenSlim
  • 811
  • 9
  • 24
0

You don't need an if statement, and I would try to avoid those in general (they're slow and sometimes convoluted to work with). You could try:

data <- data.frame(FirstName = c('Mary', 'John', 'Zhu', 'Peter'), 
                LastName = c('Higgins', 'Williams', 'Wang', 'Johnson'), 
                PhoneNumber = c("234-234-2342", "456-456-4564", "678-678-6788", "345-345-3455"))
data %>%
  filter(FirstName == "John")
0

You can use a regular expression with ^ to specify that John is at the very beginning of the string. E.g.,

names <- c("John Hogg", "Hogg John")
grep("^John", names)

[1] 1

Alternatively, you could use startswith:

startsWith(names, "John")

[1]  TRUE FALSE
erocoar
  • 5,723
  • 3
  • 23
  • 45