I have a data frame that looks like this :
| a | b | c |
|---|---|---|
| 1 | 2 | 10 |
| 2 | 2 | 10 |
| 3 | 2 | 10 |
| 4 | 2 | 10 |
| 5 | 2 | 10 |
I want to create a column with mutate function of something else under the dplyr framework of functions (or base) that will be sequence from b to c (i.e from 2 to 10 with length the number of rows of this tibble or data frame)
Ideally my new data frame I want to like like this :
| a | b | c | c |
|---|---|---|---|
| 1 | 2 | 10 | 2 |
| 2 | 2 | 10 | 4 |
| 3 | 2 | 10 | 6 |
| 4 | 2 | 10 | 8 |
| 5 | 2 | 10 | 10 |
How can I do this with R using dplyr ?
library(tidyverse)
n=5
a = seq(1,n,length.out=n)
b = rep(2,n)
c = rep(10,n)
data = tibble(a,b,c)
>Solution :
We may do
library(dplyr)
data %>%
rowwise %>%
mutate(new = seq(b, c, length.out = n)[a]) %>%
ungroup
-output
# A tibble: 5 × 4
a b c new
<dbl> <dbl> <dbl> <dbl>
1 1 2 10 2
2 2 2 10 4
3 3 2 10 6
4 4 2 10 8
5 5 2 10 10