Skip to content

Instantly share code, notes, and snippets.

@cgpu
Created March 20, 2020 20:05
Show Gist options
  • Select an option

  • Save cgpu/ee77fd74a948d1dbefdc27c97a0876ab to your computer and use it in GitHub Desktop.

Select an option

Save cgpu/ee77fd74a948d1dbefdc27c97a0876ab to your computer and use it in GitHub Desktop.
Convert of occurences of pattern in dataframe cells to other pattern
# example dataframe
b <- structure(list(Sepal.Length = c("-", "-", "-", "4.6", "5", "5.4"
), Sepal.Width = c("3.5", "-", "-", "3.1", "3.6", "3.9"), Petal.Length = c("1.4",
"1.4", "-", "-", "1.4", "1.7"), Petal.Width = c(0.2, 0.2, 0.2,
0.2, 0.2, 0.4), Species = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("setosa",
"versicolor", "virginica"), class = "factor")), row.names = c(NA, 6L), class = "data.frame")
# function
convert_all_to_from <- function(data, from, to) {
clean <- data.frame(lapply(data, function(x) {gsub(from, to, x)}))
return(clean)
}
# example command
convert_all_to_from(data = b,
from = "-",
to = NA)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment