Remove characters from the last column of a list of data frame

Viewed 99

I have a list listDF of 30 data frames (~1000 rows X 3 columns). In the last column of each one, I have a composite character as shown below :

Date        Origin              Chemical
28/10/2012  Artificial nuclides Cs-137__Sea
28/10/2012  Natural nuclides    Ra-226__Clouds
28/10/2012  Natural nuclides    Ra-228__Sands
28/10/2012  Natural nuclides    Th-228__Sea
28/10/2012  Artificial nuclides Cs-137__Rocks

For the last column of each df, how can I simply remove "__Sea", "__Clouds"... and just keep the chemical name ?

3 Answers

This may also be done with trimws from base R

listDF <- lapply(listDF, transform, 
      Chemical = trimws(Chemical, whitespace = "__.*"))

Or in tidyverse

library(stringr)
library(purrr)
library(dplyr)
listDF <- map(listDF, mutate, Chemical = str_remove(Chemical, "__.*"))

Base R solution:

## requires R version 4.1 or higher
listDF = lapply(listDF,
  \(df) {
    df[["Chemical"]] = sub(pattern = "__.*", replacement = "", df[["Chemical"]])
    df
  })
## any R version
listDF = lapply(listDF,
  function(df) {
    df[["Chemical"]] = sub(pattern = "__.*", replacement = "", df[["Chemical"]])
    df
  })

For-loop solution:

for (df in listDF){
  for (i in 1:nrow(listDF)){
    df[i, "Chemical"] = unlist(strsplit(df[i, "Chemical"], "__"))[1]
  }
}
Related