0

I'm trying to build out a function where I can specify column positions and class type.

Using the iris dataset it would look like this:

 magic_class_write <- function(df, col_nos, class_types ){

 fill in the blanks
}



library(tidyverse)

# This is how I do it now

glimpse(iris)

class(iris$Sepal.Length) <- "comma"
class(iris$Petal.Width)  <- "comma"

map(iris, class)


# This is how it will be done with the function
magic_class_write(df = iris, col_nos = c(1, 3), class_types = c("comma", "comma"))

Any ideas?

2 Answers 2

1

Using a for loop you could do:

magic_class_write <- function(df, col_nos, class_types ){
  for (i in seq_along(col_nos)) {
    class(df[[col_nos[[i]]]]) <- class_types[[i]]
  }
  df
}

iris1 <- magic_class_write(df = iris, col_nos = c(1, 3), class_types = c("comma", "comma"))
lapply(iris1, class)
#> $Sepal.Length
#> [1] "comma"
#> 
#> $Sepal.Width
#> [1] "numeric"
#> 
#> $Petal.Length
#> [1] "comma"
#> 
#> $Petal.Width
#> [1] "numeric"
#> 
#> $Species
#> [1] "factor"
Sign up to request clarification or add additional context in comments.

1 Comment

One of the benefits of using the for loop is not to do the return after the assignment
1

Using Map :

magic_class_write <- function(df, col_nos, class_types ){
  df[col_nos] <- Map(`class<-`, df[col_nos], class_types)
  return(df)
}

result <- magic_class_write(iris, c(1, 3), c("comma", "comma"))
sapply(result, class)

#Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
#     "comma"    "numeric"      "comma"    "numeric"     "factor" 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.