Writing Functions in R

Examples

Using the deathrecords.csv file, use the makeatable function to display table of values from the Sex column of the DeathRecords.

makeatable <- function(x) {prop.table(table(x, useNA="always"))}
Click to see solution
myDF <- read.csv("/anvil/projects/tdm/data/death_records/DeathRecords.csv")
makeatable <- function(x) {prop.table(table(x, useNA="always"))}

makeatable(myDF$Sex)
x
        F         M      <NA>
0.4939664 0.5060336 0.0000000

Using the deathrecords.csv file, use the makeatable function to display table of values from the MaritalStatus column of the DeathRecords.

makeatable <- function(x) {prop.table(table(x, useNA="always"))}
Click to see solution
myDF <- read.csv("/anvil/projects/tdm/data/death_records/DeathRecords.csv")
makeatable <- function(x) {prop.table(table(x, useNA="always"))}

makeatable(myDF$MaritalStatus)
x
          D           M           S           U           W        <NA>
0.152388043 0.372463819 0.126575962 0.007112043 0.341460133 0.000000000

Using the deathrecords.csv file, use the teenagecount function to display the number of teenagers in the DeathRecords data.

teenagecount <- function(x) {length(x[(x >= 13) & (x <= 19) & (!is.na(x))])}
Click to see solution
myDF <- read.csv("/anvil/projects/tdm/data/death_records/DeathRecords.csv")
teenagecount <- function(x) {length(x[(x >= 13) & (x <= 19) & (!is.na(x))])}

teenagecount(myDF$Age)
 12643