0

Can I specify data type in r for (like numeric, factor, character, etc) for each column of data frame as I import it from excel.

For example, if I have 3 columns (call them X1, X2, and X3) in a data frame (which I call X) and I want the column X1 to be a factor, column X2 to be numeric and column X3 to be character let say X (data frame) is an excel file, how do I import it into r?

1 Answer 1

1

I recommend installing readxl package by Hadley Wickham and then loading it in R.

install.packages("readxl") library(readxl) 

Then import the sheet you want in R and specifying the names and types you want

X <- read_excel("your_excel_file_name.xls (or .xlsx)", sheet = "X", col_names = c("X1", "X2", "X3"), col_types = c("factor", "numeric", "text")) 

If you hadn't specified the arguments col_names, col_types then the function read_excel would have guessed the names and types. (Note that the result will be a tibble which is very similar to a data frame and I recommend using tibbles instead of data frames)

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for you help. I tried this: X <- read_excel("C:/Users/cuty/Desktop/DATA1.xls",# sheet = "X", col_names = c("X1", "X2", "X3"), col_types = c("factor", "numeric", "text")) and got this error message: Error: Illegal column type: 'factor' [1]
@economia what data type is the column X1 in excel?
X1 is "double" in typeof(X$X1)
@economia So it contains many different real numbers. Why would you want to make this a factor? Factors are categorical variables in R. In your call replace "factor" with "double"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.