Suppose we have the following dataframe:
df <- data.frame(seq(1, 21, 1),
seq(-60, 0, 3),
seq(200, 300, 5),
sample(1:3))
colnames(df) <- c("Var1", "Var2", "Var3", "Sample")
Var1 | Var2 | Var3 | Sample |
---|---|---|---|
1 | -60 | 200 | 3 |
2 | -57 | 205 | 2 |
3 | -54 | 110 | 1 |
... | ... | ... | ... |
I want to create a new variable, whose value is selected from the column corresponding to the value in "Sample." That is, for the above the example, the result should resemble
Var1 | Var2 | Var3 | Sample | Newvar |
---|---|---|---|---|
1 | -60 | 200 | 3 | 200 |
2 | -57 | 205 | 2 | -57 |
3 | -54 | 110 | 1 | 3 |
... | ... | ... | ... | ... |
I'm working with dplyr, so tried the following, but I'm not sure how to solve the fact that paste0 is not registering "Sample" as an object:
df %>%
mutate(Newvar = !!as.symbol(paste0("Var", Sample)))
Any help would be appreciated.