Remove Last Character in R inplace

Viewed 129

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`)] <- ""
5 Answers

You could use sub here:

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

This is a perfect use case for parse_number from readr package (it is in tidyverse:

library(dplyr)
library(readr)

df %>% 
  mutate(age = parse_number(age))
   name age
1 Anon1  52
2 Anon2  62
3 Anon3  44
4 Anon4  30
5 Anon5 110

data:

df <- structure(list(name = c("Anon1", "Anon2", "Anon3", "Anon4", "Anon5"
), age = c("52a", "62", "44a", "30", "110a")), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5"))
#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

Here are two approaches. No packages are used.

1) We remove all non-digit characters where in a regular expression \D means non-digit. If we knew that only a could appear as a non-digit we could , instead, use "a" as the first argument to gsub and if we knew it only appears once we could use sub instead of gsub.

Also it is easier to debug code if you don't overwrite variables since then you always know that a particular variable is in its original state. Instead assign the result to a new variable.

transform(DF, age = as.numeric(gsub("\\D", "", age)))

This could also be written using pipes:

transform(DF, age = age |> gsub(pattern = "\\D", replacement = "") |> as.numeric())

2) We can use scan specifying that a is a comment character.

transform(DF, age = scan(text = age, comment.char = "a", quiet = TRUE))

Note

Lines <- "
    name   age
1  Anon1   52a
2  Anon2   62
3  Anon3   44a
4  Anon4   30
5  Anon5   110a"
DF <- read.table(text = Lines)

The inplace modifier in python refers to making a change without creating a copy. The data.table package in R allows for this (called replace by reference).

df <- read.table(text="
   name   age
1  Anon1   52a
2  Anon2   62
3  Anon3   44a
4  Anon4   30
5  Anon5   110a")

library(data.table)
library(stringi)
setDT(df)[, age:=stri_extract(age, regex='^\\d+')]
df

The first clause (setDT(df)) converts df to a data.table by reference (e.g., without making a copy), and the second clause ([, age:=...]) replaces the values in column age with ... also by reference.

Related