Home > Mobile >  How can I create a new column with mutate function in R that is a sequence of values of other column
How can I create a new column with mutate function in R that is a sequence of values of other column

Time:10-12

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)

CodePudding user response:

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

CodePudding user response:

If you want this done "by group" for each a value (creating many new rows), we can create the sequence as a list column and then unnest it:

data %>%
  mutate(result = map2(b, c, seq, length.out = n)) %>%
  unnest(result)
# # A tibble: 25 × 4
#        a     b     c result
#    <dbl> <dbl> <dbl>  <dbl>
#  1     1     2    10      2
#  2     1     2    10      4
#  3     1     2    10      6
#  4     1     2    10      8
#  5     1     2    10     10
#  6     2     2    10      2
#  7     2     2    10      4
#  8     2     2    10      6
#  9     2     2    10      8
# 10     2     2    10     10
# # … with 15 more rows
# # ℹ Use `print(n = ...)` to see more rows

If you want to keep the same number of rows and go from the first b value to the last c value, we can use seq directly in mutate:

data %>%
  mutate(result = seq(from = first(b), to = last(c), length.out = n()))
# # A tibble: 5 × 4
#       a     b     c result
#   <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

CodePudding user response:

This one?

library(dplyr)
df %>% 
  mutate(c1 = a*b)
  a b  c c1
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
  • Related