0

Appreciate any help on this, I am relatively new to R and stackoverflow.

Here is some sample code to work with for my problem, it is from a database of injured workers.

Area <- c("Connecticut", "Maine", "Massachusetts", "New Hampshire")
X2004 <- c(0,1,4,1)
X2005 <- c(1,0,6,2) 
df1 <- data.frame(Area, X2004, X2005) 

I would like to write a simple script that takes a number of injured workers and returns the "Area" and year in which a specific number of officers were killed. E.g "6" would return X2005 and Massachusetts, and 1 would return X2004 Connecticut and X2005 Maine. Along the lines of Vlookup in Excel.

The closer to base R the better, I am doing this as part of an exercise on indexing. I haven't found any solutions with tidyverse either.

Thanks in advance for your help, I'm sure there is a clear solution just beyond my reach!

Aaron
  • 109
  • 5
  • Possible duplicate of [How to do vlookup and fill down (like in Excel) in R?](https://stackoverflow.com/questions/15303283/how-to-do-vlookup-and-fill-down-like-in-excel-in-r) – Maurits Evers Sep 05 '18 at 14:05
  • Check out this answer https://stackoverflow.com/questions/9931241/how-do-i-retrieve-a-matrix-column-and-row-name-by-a-matrix-index-value And get the index by using `lookup <- 6` and then `which(df == lookup), dim(df1))` – P1storius Sep 05 '18 at 14:29
  • `df1 %>% gather(year, value, -Area) %>% filter(value == 6)`? – Axeman Sep 05 '18 at 14:29

1 Answers1

1

You can using melt from reshape

newdf1=reshape::melt(df1)
newdf1[newdf1$value==6,c('Area','variable')]
           Area variable
7 Massachusetts    X2005
BENY
  • 317,841
  • 20
  • 164
  • 234