I recently asked how to use dictionary files to recode values in a dataset (Working with data values (dictionary). dataframes and recoding in R)
I am with a simpler problem, but that fix isn't working. Suppose I have the following dataset, each row is a geographical unit, and column V1 lists the "first neighbor" that a geographical package found, but lists it using the row number:
V1 <- c(1, 2, 1)
id <- c(110001, 110002, 110003)
dataset <- as.data.frame(matrix(c(id, V1), ncol=2))
colnames(dataset) <- c("id", "V1")
So on this dataset, region 110001 is a neighbor of itself (V1 = 1), and region 110003 is a neighbor of 110001 (V1 = 1).
Now, instead of displaying V1 (first neighbor) as "1, 2, 1", I'd like it to be the id of the geographic region, "110001, 110002, 110001".
So, I create a "dictionary" file that contains the rownumber and id of the geographic region:
dictionary <- as.data.frame(matrix(c(dataset$id, 1:nrow(dataset)),ncol=2))
colnames(dictionary) <- c("id","row")
Then, I try to map these using a mutate. Note that I have many neighborhood variables (V1-V30), and I'm only using one in the example, so I will use syntax that translates to all:
new_dataset <- dataset %>% mutate(across(starts_with("V"), ~subset(dictionary, row == cur_column(), select= id)))
What this should do is: run across columns, compare values to the values at the rows of the dictionary, and then return the appropriate id. It seems that the problem is the repeated entries in dataset$V1 (in this example, rows 1 and 3 are equal to "1"). If I proceeded row-by-row, this would work:
first_row <- dataset[1,] %>% mutate(V1 = subset(dictionary, row == V1, select= id))
second_row <- dataset[2,] %>% mutate(V1 = subset(dictionary, row == V1, select= id))
third_row <- dataset[3,] %>% mutate(V1 = subset(dictionary, row == V1, select= id))
My impression is that "subset" is ignoring repeated entries. E.g., if I run this:
subset(dictionary, row == dataset$V1, select= id)
It should return "110001, 110002, 110001", but only returns "110001, 110002".
Any ideas on how to make subset return everything or another approach to this?