FPL
FPL

Reputation: 466

Correct use of str_replace_all within a function

I'm trying to use str_replace_all within a user-defined function in r to replace all instances of the letter 'T' in a column in a data frame with a space. The function also removes the last letter from each string.

Desired output

For the data below, this would convert the first table into the second when the column df$code is passed through:

id    code
1     STWX
2     STVX
3     RTUX

id    code
1     S W
2     S V
3     R U

Previous attempts

I've tried using the following:

str_convert <- function(x) {
str_replace_all(x, 'T', ' ')
substr(x,1,nchar(x)-1)
}

However, the output I get doesn't remove the 'T', so the final output looks like this:

id    code
1     STW
2     STV
3     RTU

Am I making an obvious mistake? Any help greatly appreciated.

Upvotes: 0

Views: 464

Answers (2)

MartijnVanAttekum
MartijnVanAttekum

Reputation: 1435

and the tidyverse solution:

df <- data.frame(id = 1:3, code = c("STWX", "STVX", "RTUX"))

str_convert <- function(x) {
  str_replace_all(x, 'T', ' ') %>%
  str_sub(1, -2)
}

df %>% 
   mutate(code = str_convert(code))
  id code code
1  1 STWX S W
2  2 STVX S V
3  3 RTUX R U

This forwards the output from str_replace_all as the first argument of str_sub, of which the result is subsequently returned by the function. str_sub can also have a negative stop value (counting back from the end), which is convenient here.

Upvotes: 1

jyjek
jyjek

Reputation: 2707

Try this one

str_convert <- function(x) {
   r <- str_replace_all(x, 'T', ' ')
   r <- substr(r,1,nchar(r)-1)
 return(r)
   }

 df1 %>% 
   mutate(res = str_convert(code))
  id code res
1  1 STWX S W
2  2 STVX S V
3  3 RTUX R U

Upvotes: 1

Related Questions