Search code examples
rvariablesdata.tablecol

How do I create a new column in R with variable look up? R programming


I have a data table that looks like:

    Cause of Death                Ethnicity                 Count
1: ACCIDENTS EXCEPT DRUG POISONING ASIAN & PACIFIC ISLANDER  1368
2: ACCIDENTS EXCEPT DRUG POISONING                 HISPANIC  3387
3: ACCIDENTS EXCEPT DRUG POISONING       NON-HISPANIC BLACK  3240
4: ACCIDENTS EXCEPT DRUG POISONING       NON-HISPANIC WHITE  6825
5:              ALZHEIMERS DISEASE ASIAN & PACIFIC ISLANDER   285
---    

I'd like to create a new column that is simply the percent of people between ethnicities that pass away from a a specific cause of death. Like so:

   Cause of Death                Ethnicity                  Count  PercentofDeath
1: ACCIDENTS EXCEPT DRUG POISONING ASIAN & PACIFIC ISLANDER  1368     0.09230769
2: ACCIDENTS EXCEPT DRUG POISONING                 HISPANIC  3387     0.22854251
3: ACCIDENTS EXCEPT DRUG POISONING       NON-HISPANIC BLACK  3240     0.21862348
4: ACCIDENTS EXCEPT DRUG POISONING       NON-HISPANIC WHITE  6825     0.46052632
5:              ALZHEIMERS DISEASE ASIAN & PACIFIC ISLANDER   285     0.04049446
---   

Here's my code to do it, which is quite ugly:

   library(data.table)
   #load library, change to data table
   COD.dt <- as.data.table(COD)


   #function for adding the percent column
   lala  <- function(x){ 

   #see if I have initialized data.table I'm going to append to


      if(exists("started")){
        p <- COD.dt[x ==`Cause of Death`]
        blah <- COD.dt[x ==`Cause of Death`]$Count/sum(COD.dt[x ==`Cause of Death`]$Count)
        p$PercentofDeath <- blah
        started <<- rbind(started,p)
      }

       #initialize data table
        else{
            l <- COD.dt[x ==`Cause of Death`]
            blah <- COD.dt[x ==`Cause of Death`]$Count/sum(COD.dt[x ==`Cause of Death`]$Count)
            l$PercentofDeath <- (blah)
            started <<- l  
        }

 #if finished return
if(x == unique(COD.dt$`Cause of Death`)[length(unique(COD.dt$`Cause of Death`))]){
  return(started)
 }
 }

 #run function
 h <- sapply(unique(COD.dt$`Cause of Death`), lala)
  #remove from environment
 rm(started)
 #h is actually ends up being a list, the last object happen to be the one I want so I take that one
 finalTable <- h$`VIRAL HEPATITIS`  

So, as you can see. This code is quite ugly, and not adaptable. I was hoping from some guidance as to how to make this better. Maybe using dpylr, or some other function?

Best


Solution

  • A pure data-table solution will be easy as well, but here's dplyr:

     library(dplyr)
    
    COD.dt %>% group_by(`Cause of Death`) %>%
        mutate(PercentofDeath = Count / sum(Count))
    

    You could turn this into a function, but it's such a small, basic operation that most people wouldn't bother.