Count the number of rows
dat1 = data.frame(ID = c(100,100,200), Name = c('Ha', NA, 'Ly'), Age = c(30,0,NA), stringsAsFactors = FALSE)
#Use: stringAsFactors for changing factor level in data frame into correct format (in this case: Name has chr type, Age has num type)
dat1
## ID Name Age
## 1 100 Ha 30
## 2 100 <NA> 0
## 3 200 Ly NA
length(unique(dat1[,c("ID")])) #Count the number of unique ID
## [1] 2
length(unique(dat1[,c("Name")])) #Count the number of unique name
## [1] 3
nrow(unique(dat1[,c("ID","Name")])) #Count the number of unique (ID and Name)
## [1] 3
length(unique(dat1[,c("ID","Name")])) #Count the number of column
## [1] 2
Notice: Difference between using length and nrow
length: count the number of values in a vector.
nrow: count the number of rows in a table. Because ID and Name in dat1 created a table, so we need to use nrow to count rows. If we use length, it will count the number of column in dat1.