David David - 3 months ago 21
R Question

R - How do I add a new column to a dataframe that is the calculated result of another column

I'm trying to write a function in R that maps input information to outputs, but retains the input in the same data frame. I have a function that I wrote that will take the input and provide the correct output for single values, but I lack the R knowledge to know how to rewrite this so I can pass in a vector.

I want to pass it in a frame, and add a new column to the dataframe. Example code below:

d <- data.frame(Type=c("_Swap_","Nothing","CAP", "FLOOR", "FLOOR", "BLAH", "Digital", "Something!"))

d$newType= createTags(d$Type)

createTags = function(Type){
map = data.frame(input=c("Swap","Note","Option", "Floor", "FLOOR", "CAP", "Digital", "Bond"),
output=c("Swap","Note","Option", "CapFloor", "CapFloor", "CapFloor", "CapFloor", "Bond"))

tag="Unknown"

print(length(Type))

for (j in 1:NROW(map)) {
input = map[j,]$input
output = map[j,]$output

ifelse (grepl(toupper(input), toupper(Type))){
tag = output
}
}

return(tag)
}


So in the output I want d to have two columns, one is the original Type, and then at the end there should be a second column called newType.

Answer

I ended up playing around with this alot. Thanks Mark Timms for the help, although I realised I needed to use grepl to make sure that I could cover all the cases

SRTLondon <- 
   data.frame(Type=c("_Swap_","Nothing","CAP", "FLOOR", "FLOOR", "BLAH", "Digital", "Something!"))

createTags = function(Type){
   #browser()
   map = data.frame(input=c("Swap","Note","Option", "Floor", "FLOOR", "CAP", "Digital", "Bond"), 
               output=c("Swap","Note","Option", "CapFloor", "CapFloor", "CapFloor", "CapFloor", "Bond"),stringsAsFactors = F)

   work = data.frame(x=toupper(Type),stringsAsFactors = F)
   work$tag="NA"

   for (i in 1:NROW(work)) {  
    check = work$x[i]

    for (k in 1:nrow(map)){
      input = map[k,'input']
      output = map[k,'output']

      if(grepl(toupper(input),check))
      {
        work$tag[i]=output
        break
      }

    }

  }
  return(work$tag)
}

SRTLondon$type.tags= createTags(SRTLondon$Type)