'How to select specific cases within one variable to create a new variable?

I have a 'telephone' variable where one participant may have put their landline number, whilst others have put their mobile number. I want to pull out all the landline numbers from this variable and put them in their own column. So I end up with 2 columns, a mobile number column and a landline column in my data frame, rather than just the one telephone variable. I've tried to do this with the 'starts_with' function as all landline numbers start with '01'.

So my data looks something like this:

participant Number
1 07710 123456
2 01254 456789
3 07720 666333

But I want to be able to select all the numbers that start with '01' and put them in their own column, so my output would look something like this:

Participant Number Number2
1 07710 123456
2 01254 456789
3 07720 666333

Is there a way of doing this please? Or is there a way of deleting the numbers that start with '01'? I don't want to delete the row as participant 2 has valuable info in other variables in the data frame. Many thanks in advance :)



Solution 1:[1]

You could:

numbr <- c('016097751673', '6097751673', '017736440981', '015059811232')
mobl <- NA
phone <- data.frame(numbr, mobl)
phone
         numbr mobl
1 016097751673 <NA>
2   6097751673 <NA>
3 017736440981 <NA>
4 015059811232 <NA>

phone$mobl <- grepl('^01', phone$numbr)
phone
         numbr  mobl
1 016097751673  TRUE
2   6097751673 FALSE
3 017736440981  TRUE
4 015059811232  TRUE

The grepl pattern `'^01', says look for '01' at the beginning of the string in phone$numbr, assign TRUE or FALSE if the patterns is found.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1