To check data type of each column of data frame, you can use class function or str() function. You can use class() function with lapply() or sapply() function.
The following methods show how you can do it with syntax.
Method 1: Use class() With lapply() Function
lapply(df, class)
Method 2: Use class() With sapply() Function
sapply(df, class)
Method 3: Use str() Function
str(df)
The following examples show how to check data type of each column of data frame in R.
Using class() With lapply() Function
Let’s see how we can check data type of each column of data frame:
# Create data frame
df <- data.frame(Start_date=as.Date(c("2000-05-21","1998-03-28","2001-01-19","2003-04-27","2004-11-26","2008-11-25")),Machine_name = c("Machine1","Machine2","Machine3","Machine4","Machine5","Machine6"),Value = c(110,120,135,95,98,92),Working= c(TRUE,TRUE,FALSE,TRUE,FALSE,FALSE))
# Check datatype
lapply(df,class)
Output:
$Start_date
[1] "Date"
$Machine_name
[1] "character"
$Value
[1] "numeric"
$Working
[1] "logical"
The output shows data type of each column of data frame.
Using class() With sapply() Function
Let’s use class() function with sapply() to check data type in R:
# Create data frame
df <- data.frame(Start_date=as.Date(c("2000-05-21","1998-03-28","2001-01-19","2003-04-27","2004-11-26","2008-11-25")),Machine_name = c("Machine1","Machine2","Machine3","Machine4","Machine5","Machine6"),Value = c(110,120,135,95,98,92),Working= c(TRUE,TRUE,FALSE,TRUE,FALSE,FALSE))
# Check datatype
sapply(df,class)
Start_date Machine_name Value Working
"Date" "character" "numeric" "logical"
Here the output shows data type of each column of data frame
Use str() Function
Let’s see how we can use str() function in R:
# Create data frame
df <- data.frame(Start_date=as.Date(c("2000-05-21","1998-03-28","2001-01-19","2003-04-27","2004-11-26","2008-11-25")),Machine_name = c("Machine1","Machine2","Machine3","Machine4","Machine5","Machine6"),Value = c(110,120,135,95,98,92),Working= c(TRUE,TRUE,FALSE,TRUE,FALSE,FALSE))
# Check data type
str(df)
Output:
'data.frame': 6 obs. of 4 variables:
$ Start_date : Date, format: "2000-05-21" "1998-03-28" "2001-01-19" ...
$ Machine_name: chr "Machine1" "Machine2" "Machine3" "Machine4" ...
$ Value : num 110 120 135 95 98 92
$ Working : logi TRUE TRUE FALSE TRUE FALSE FALSE
Here output shows not only datatype of each column but also it shows number of rows and columns.