简体   繁体   中英

Cannot pass column names to function in r

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.

You could make your function work by using eg as.formula :

## create functions
x <- function(data, name){
  fmla <- as.formula(paste("~", name))
  dummy <- model.matrix(fmla, data)[,-1] %>% head()
  return(dummy)
}

## test functions
x(dat_train, "Pclass")
#>   Pclass2 Pclass3
#> 1       0       1
#> 2       0       0
#> 3       0       1
#> 4       0       0
#> 5       0       1
#> 6       0       1

Created on 2021-01-02 by the reprex package (v0.3.0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM