In a dpylr pipline how to use sample and seq

0 votes

 I have a dataframe consisting of two columns set1 & set2, create a new variable that is a randomly selected value between set1 and set2 (inclusive and equal probability) using dplyr.

I got an error

library(tidyverse)

data_frame(set1 = 1:10, set2 = 11) %>% mutate(rand_btwn = base::sample(seq(set1, set2, by = 1), size = 1))

Apr 6, 2018 in Data Analytics by DataKing99
• 8,250 points
• 3,262 views

1 answer to this question.

0 votes

For avoiding rowwise(), I prefer to use map() in mutate(), because for rowwise() there will be an unnecessary grouping creates.

set.seed(123)
data_frame(set1 = 1:10, set2 = 11) %>%
  mutate(rand_btwn = map_int(map2(set1, set2, seq), sample, size = 1))

 

## # A tibble: 10 x 3

#      set1  set2 rand_btwn
#    <int> <dbl>     <int>
#  1     1    11         4
#  2     2    11         9
#  3     3    11         6
#  4     4    11        11
#  5     5    11        11
#  6     6    11         6
#  7     7    11         9
#  8     8    11        11
#  9     9    11        10
# 10    10    11        10
answered Apr 6, 2018 by DeepCoder786
• 1,720 points

edited Jun 9, 2020 by Gitika