-2

Currently I wish to lookup a value from below table in R. For example, if I execute

eval(parse("Tableg1004"))

I would get the value from column g and row 1004 which is "Y".

Table  c g s o
 1000  2 N N N
 1001  3 Y N N
 1002  5 Y Y N
 1003  9 Y N N
 1004 11 Y N N
 1005 13 N N Y

How could I achieve this?

Eng Kheng
  • 5
  • 1

1 Answers1

0

I don't think we should/can use eval parse expression here (see link above in comment from Ronak Shah). Ok - maybe we could. But we definitively shouldn't. What we could do instead is either join the 'lookup table' to the data:

lookup_table <- read.table(text="Table  c g s o
 1000  2 N N N
 1001  3 Y N N
 1002  5 Y Y N
 1003  9 Y N N
 1004 11 Y N N
 1005 13 N N Y", header=T, stringsAsFactors=F)

data_table <- data.frame(Table = 1000:1007,
                         v1 = 1:8)

data_table_joined <- merge(data_table, lookup_table[, c("Table", "g")], by="Table", all.x=TRUE)


  Table v1 g
1  1000  1 N
2  1001  2 Y
3  1002  3 Y
4  1003  4 Y
5  1004  5 Y
6  1005  6 N
7  1006  7 NA
8  1007  8 NA

Or we create a function that takes the value of the column to extract as a parameter:

look_up <- function(t, c) {
  f <- function(t, c) {
    r <- lookup_table[lookup_table$Table %in% t, c]
    return(ifelse(is.null(r), NA, r))
  }
  return(unlist(mapply(FUN = f, t, c)))
}

We can use this function like this:

look_up(c(1005, 1005), c("g", "o"))

Or even like that:

library(dplyr)
data_table %>% 
  mutate(from_lookup = look_up(Table, "o"))


  Table v1 from_lookup
1  1000  1           N
2  1001  2           N
3  1002  3           N
4  1003  4           N
5  1004  5           N
6  1005  6           Y
7  1006  7        <NA>
8  1007  8        <NA>
dario
  • 6,415
  • 2
  • 12
  • 26