Possible Duplicate:
Filtering a data frame by factors in R
I wrote a simple function to map a variable against a table and return the value in a corresponding column. The idea is very the same as vlookup in Excel. The function I wrote is the following:
ApplyMap <- function(mappingtable,variable){
if(ncol(mappingtable)!=2){
"Mapping table needs to have two columns"
}else{
names(mappingtable) <- c("col1","col2")
output <- mappingtable[col1==variable]$col2[1]
output <- as.character(if(is.na(output)){variable}else{output})
return(output)
}
}
My map:
require(data.table)
mapping <- structure(list(Field1 = structure(c(4L, 1L, 2L, 3L), .Label = c("Amsterdam",
"Arnhem", "Groningen", "Rotterdam"), class = "factor"), Field2 = structure(c(4L,
3L, 1L, 2L), .Label = c("Gelderland", "Groningen", "Noord-Holland",
"Zuid-Holland"), class = "factor")), .Names = c("Field1", "Field2"
), row.names = c(NA, -4L), class = c("data.table", "data.frame"
), .internal.selfref = <pointer: 0x7f93f1018578>)
When I apply this to a simple variable such as:
ApplyMap(mapping,"Arnhem")
[1] "Gelderland"
or
ApplyMap(mapping,"New York")
[1] "New York"
it seems to be working fine. However, now I would like to apply it to the following data.table and add another column with the second column in the map where appropriate. The list is the following:
list <- structure(list(List = structure(c(6L, 1L, 2L, 3L, 4L, 5L, 7L), .Label = c("Amsterdam",
"Arnhem", "Groningen", "Haarlem", "Maastricht", "Rotterdam",
"Utrecht"), class = "factor")), .Names = "List", class = "data.frame", row.names = c(NA,
-7L))
I try to do this with the following code:
list$Province <- ApplyMap(mapping,list$List)
Unfortunately this does not seem to work appropriately. Is there anybody who can help me to understand why it is not working correctly? I get the following error message when I execute the line above:
Error in Ops.factor(col1, variable) : level sets of factors are different
Obvious, I would like to get second column to the table with the values from the second column of the mapping-table.