I try to create a function to generate dummy variables, but I find the column name cannot be recognized when I create a trail function.
here is my code:
library(tidyverse)
library(tidyr)
library(gridExtra)
## set the file path
file = "https://raw.githubusercontent.com/Carloszone/Kaggle-Cases/main/01-Titanic/train.csv"
## load data and name it "dat_train"
dat_train = read.csv(file)
## transform columns' data types
dat_train <- dat_train %>% transform(PassengerId = as.character(PassengerId),
                                     Survived = as.factor(Survived),
                                     Pclass = as.factor(Pclass),
                                     Sex = as.factor(Sex),
                                     SibSp = as.factor(SibSp),
                                     Parch = as.factor(Parch),
                                     Ticket = as.character(Ticket),
                                     Cabin = as.character(Cabin),
                                     Embarked = as.factor(Embarked)
)
## create functions
x <- function(data, name){
  dummy <- model.matrix(~name, data)[,-1] %>% head()
  return(dummy)
}
y <- function(data){
  dummy <- model.matrix(~Pclass, data)[,-1] %>% head()
  return(dummy)
}
## test functions
x(dat_train, "Pclass")
y(dat_train)
At first, I create the function "x", but I find it doesn't work:
 Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : 
  contrasts can be applied only to factors with 2 or more levels 
Therefore, I create the function "y", and it runs well.
  Pclass2 Pclass3
1       0       1
2       0       0
3       0       1
4       0       0
5       0       1
6       0       1
So, I think the question is the column name fail to pass to the function. But I don't know how to deal with the problem.
 
    