Manually defining the variables

As the data file I imported does not contain the variable names, I set them using the R function names(). This code ran without an issue:

#Add names to the dataset
names(Data) <- c("Gender", "Age", "MonthlyExpenses", "MaritalStatus", "HomeStatus", "Occupation", "BankingInstitution", "YearsEmployed", "NoPriorDefault", "Employed", "CreditScore", "DriversLicense", "AccountType", "MonthlyIncome", "AccountBalance", "Approved")

However, the following code produces an error:

> # Manually define the variables
> 
> Data$Gender <- as.factor(Data$Gender) 
Error in is.factor(x) : object 'Data' not found
> Data$Age <- as.numeric(Data$Age)
Error: object 'Data' not found
> Data$MonthlyExpenses <- as.integer(Data$MonthlyExpenses) 
Error: object 'Data' not found
> Data$MaritalStatus <- as.factor(Data$MaritalStatus) 
Error in is.factor(x) : object 'Data' not found
> Data$HomeStatus <- as.factor(Data$HomeStatus) 
Error in is.factor(x) : object 'Data' not found
> 

Why is the error occurring, given that I created "names(Data)" prior to defining the variables?

Apparently there is no any dataframe object called Data in your working environment. Therefore, it cannot find it. Are you sure that you created it in the right way? I produced a small example here, your code actually worked.

Data <- data.frame(a = c(1, 2, 2, 1), b = c(5, 6, 7, 8))
names(Data) <- c("Gender", "Age")
Data
  Gender Age
1      1   5
2      2   6
3      2   7
4      1   8

Data$Gender <- as.factor(Data$Gender) 
Data$Age <- as.numeric(Data$Age)
str(Data)
'data.frame':	4 obs. of  2 variables:
 $ Gender: Factor w/ 2 levels "1","2": 1 2 2 1
 $ Age   : num  5 6 7 8
2 Likes

Thank you! I have renamed the file..... so this now works.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.