Reputation: 916
What I have:
data
0_x 1_x 2_x ...10_x num_col
0.2 0.3 0.4 2
0.3. 0.5 0.3 1
0 0.2 0.8 3
what I want:
0_x 1_x 2_x ...10_x num_col value
0.2 0.3 0.4 . 2 0.3
0.3. 0.5 0.3 . 1 0.3
0 0.2 0.8 . 3 0.8
basically I want to create a column with the value corresponding to the column indicated by "num_col"
Upvotes: 1
Views: 31
Reputation: 39858
One option involving dplyr
could be:
df %>%
rowwise() %>%
mutate(value = get(paste0(num_col-1, "_x"))) %>%
ungroup()
`0_x` `1_x` `2_x` num_col value
<dbl> <dbl> <dbl> <int> <dbl>
1 0.2 0.3 0.4 2 0.3
2 0.3 0.5 0.3 1 0.3
3 0 0.2 0.8 3 0.8
It does, however, assume that your columns are named in a certain way.
Sample data:
df <- structure(list(`0_x` = c(0.2, 0.3, 0), `1_x` = c(0.3, 0.5, 0.2
), `2_x` = c(0.4, 0.3, 0.8), num_col = c(2L, 1L, 3L)), class = "data.frame", row.names = c(NA,
-3L))
Upvotes: 1