I have the following dataframe df:
indx adj_coords explore_ind
1 1 2, 3, 4 dark
2 2 1, 3, 5 dark
3 3 1, 2, 4 light
4 4 1, 3, 5 dark
5 5 1, 4, 5 light
df<-structure(list(indx = 1:5, adj_coords = list(2:4, c(1L, 3L, 5L), c(1L, 2L, 4L), c(1L, 3L, 5L), c(1L, 4L, 5L)), explore_ind = c("dark",
"dark", "light", "dark", "light")), row.names = c(NA,
5L), class = "data.frame")
I would like to add another column called adj_coords_explore_ind that tells us whether the row given in the adj_cord is dark or light. The result would look something like:
indx adj_coords explore_ind adj_coords_explore_ind
1 1 2, 3, 4 dark dark, light, dark
2 2 1, 3, 5 dark dark, light, light
3 3 1, 2, 4 light dark, dark, dark
4 4 1, 3, 5 dark dark, light, light
5 5 1, 4, 5 light dark, dark, light
CodePudding user response:
df$adj_coords_explore_ind <- map(df$adj_coords, ~ df$explore_ind[.x])
CodePudding user response:
One option could be:
within(df, adj_coords_explore_ind <- lapply(adj_coords, function(x) explore_ind[match(x, indx)]))
indx adj_coords explore_ind adj_coords_explore_ind
1 1 2, 3, 4 dark dark, light, dark
2 2 1, 3, 5 dark dark, light, light
3 3 1, 2, 4 light dark, dark, dark
4 4 1, 3, 5 dark dark, light, light
5 5 1, 4, 5 light dark, dark, light