Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I create a new column with mutate function in R that is a sequence of values of other columns in R?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading