Home > Software engineering >  Remove Last Character in R inplace
Remove Last Character in R inplace

Time:04-09

I came from a Python background and I am working in R with this data df.

    name   age
1  Anon1   52a
2  Anon2   62
3  Anon3   44a
4  Anon4   30
5  Anon5   110a

Using R language, how can I remove the a in the last part of the age column and do data modification in place??

(just like Python using inplace=True)

Can I attain it using

df$Age[which(df$Age == `a pattern`)] <- ""

CodePudding user response:

You could use sub here:

df$age <- sub("a$", "", df$age, fixed=TRUE)

CodePudding user response:

#A tidy solution
library(dplyr)
library(stringr)

df <- data.frame(name=c("anon1","anon2"),age=c("52","37a"))

df <- df %>%
  mutate(age = str_extract(age,"^\\d "))

df
   name age
1 anon1  52
2 anon2  37
  • Related