I have a data frame where the last column is the name of a column within the data frame that I want to extract from. See this example:
library(tidyverse)
# Sample Data
df = tibble(x = c(1,2,3), y = c(4,5,6), columnIndicator = c("x","x","y"))
df %>%
mutate(newValue = !!as.name(df$columnIndicator))
## desired value for df$newValue is c(1,2,6), but returns c(1,2,3)
The solution should be simple, but I am in what feels like a mental rut. Thanks for any advice
I think the easiest way is to make the data tidier. If each observation has either the x or y value, create observations for both and then filter to the ones you want.
df[["id"]] <- seq_len(nrow(df))
df %>%
gather("column", "newValue", x, y) %>%
filter(column == columnIndicator) %>%
select(-columnIndicator, -column) %>%
right_join(df, by = "id")
# # A tibble: 3 x 5
# id newValue x y columnIndicator
# <int> <dbl> <dbl> <dbl> <chr>
# 1 1 1 1 4 x
# 2 2 2 2 5 x
# 3 3 6 3 6 y
Sadly that doesn't work if df is a tibble because all together now "tibbles are not a drop-in replacement for data frames". Also that code returns a character value for newValue because there's a character column in the data frame, but lop that out and everything is numeric again.
You are all fantastic!!! I love all the options and I think many of them will find their way into solutions for others. For me, I am a tidyverse purist and hence, selected the solution by @nwerth.
I cannot be grateful enough for this wonderful community with these great contributions from @nwerth@JohnMount and @geospacedman. Thanks!