rep() with each equals a vector
rep(1:5, vect1)
If you have questions about how to work functions in R, try
?function
where "function" is whatever function you want to know about. From ?rep
you would have read:
'times' A integer vector giving the (non-negative) number of times to repeat
each element if of length length(x), or to repeat the whole vector if
of length 1. Negative or NA values are an error.
Recursively repeat vector elements N times each
rep(v, each=3)
or
rep(v, each=n)
where you have n defined
Create a repeating vector sequence using named vector of counts
rep( resp, times = counts)
Use the base function rep
Repeating elements in a vector with a for loop
Use the rep
function, along with the possibility to use recycling logical indexing ...[c(TRUE, FALSE, TRUE, TRUE)]
rep(3:50, each = 2)[c(TRUE, FALSE, TRUE, TRUE)]
## [1] 3 4 4 5 6 6 7 8 8 9 10 10 11 12 12 13 14 14 15 16 16 17 18 18 19
## [26] 20 20 21 22 22 23 24 24 25 26 26 27 28 28 29 30 30 31 32 32 33 34 34 35 36
## [51] 36 37 38 38 39 40 40 41 42 42 43 44 44 45 46 46 47 48 48 49 50 50
If you use a logical vector (TRUE
/FALSE
) as index (inside [
]
), a TRUE
leads to selection of the corresponding element and a FALSE
leads to omission. If the logical index vector (c(TRUE, FALSE, TRUE, TRUE)
) is shorter than the indexed vector (rep(3:50, each = 2)
in your case), the index vector is recyled.
Also a side note: Whenever you use R code like
x = c(x, something)
or
x = rbind(x, something)
or similar, you are adopting a C-like programming style in R. This makes your code unnessecarily complex and might lead to low performance and out-of-memory issues if you work with large (say, 200MB+) data sets. R is designed to spare you those low-level tinkering with data structures.
Read for more information about the gluttons and their punishment in the R Inferno, Circle 2: Growing Objects.
Need help understandig the 'rep()' function
In R, rep
is a function. It is designed to replicate its first argument a number of times equal to its second argument. Thus rep(2, 5)
returns a vector of length 5 with each element as 2.
In R, functions are also objects, and when you input a function's name, R will return the something that tries to be useful by showing that the input is a function and providing the expected arguments. The .Primitive("rep")
part tells you that rep
is a primitive function, part of the base R code.
rep
function (x, ...) .Primitive("rep")
In this case, rep
requires at least one argument x
, which the object to be replicated. The ...
indicates that it can take a number of other optional arguments. To learn about them, you can access the help file for rep
with ?rep
.
You can call rep
with more arguments, but the behavior might not be what you expect.
Create a vector by repeating values in a data frame
Adding comment as answer to help future users.
You can get this effect using rep
like so:
x <- c(1,2,3)
y <- c(2,3,4)
vec <- rep(x, y)
vec
# [1] 1 1 2 2 2 3 3 3 3
How to know if a vector is composed by the same elements?
An option is diff
.
diff(vec1)
If the elements are equal, their difference is zero.
all(diff(vec1) == 0)
#[1] TRUE
Or compare the vector to its first element.
all(vec1 == vec1[1])
#[1] TRUE
Edit.
Several ways of determining if all elements of a vector are equal were posted, see RHertel, Yuriy Saraykin, tmfmnk. Here are comparative tests.
library(microbenchmark)
library(ggplot2)
f <- function(n){
x <- rep(10, n)
mb <- microbenchmark(
var = var(x) == 0,
sd = sd(x) == 0,
diff = all(diff(x) == 0),
extract = all(x == x[1]),
unique = length(unique(x)) == 1
)
mb
}
sizes <- c(10, 100, seq(1e3, 1e4, by = 1e3))
mb_list <- lapply(sizes, f)
names(mb_list) <- sizes
res <- lapply(seq_along(mb_list), function(i){
agg <- aggregate(time ~ expr, mb_list[[i]], median)
agg$size <- sizes[i]
agg
})
res <- do.call(rbind, res)
ggplot(res, aes(size, time, colour = expr)) +
geom_point() +
geom_line()
Repeat down a column with an unequal number of values
How do I specific how many times a specific value repeats?
The times
argument. From ?rep
:
times
an integer-valued vector giving the (non-negative) number of times to repeat each element if of lengthlength(x)
, or to repeat the whole vector if of length 1
> rep(c("Week 1", "Week 2", "Week 3"), times = c(10, 20, 30))
# repeats "Week 1" 10 times, "Week 2" 20 times, "Week 3" 30 times
Create vector with number of each type of item determined by another vector
We can use the rep
function as well as seq.Date
to do this:
Create Data
set.seed(123)
kvec <- sample(0:10, 365, replace = T) #create the nonnegative integers
#create sequence of dates
date_vec <- seq.Date(from = as.Date('2015-01-01'), to = as.Date('2015-12-31'), by = 'day')
Use rep()
#let rep() do the work
k_date_vec <- rep(date_vec, times = kvec)
Result
head(kvec)
[1] 3 8 4 9 10 0
head(k_date_vec)
[1] "2015-01-01" "2015-01-01" "2015-01-01" "2015-01-02" "2015-01-02" "2015-01-02"
Related Topics
How to Count Runs in a Sequence
Unlist Data Frame Column Preserving Information from Other Column
Clang-7: Error: Linker Command Failed With Exit Code 1 For Macos Big Sur
Read All Worksheets in an Excel Workbook into an R List With Data.Frames
Wrap Long Axis Labels Via Labeller=Label_Wrap in Ggplot2
How to Extract Plot Axes' Ranges For a Ggplot2 Object
Replace Multiple Letters With Accents With Gsub
Concatenate Strings by Group With Dplyr
Why Is the Parallel Package Slower Than Just Using Apply
Chopping a String into a Vector of Fixed Width Character Elements
Summarizing by Subgroup Percentage in R
A Comprehensive Survey of the Types of Things in R; 'Mode' and 'Class' and 'Typeof' Are Insufficient
Change Variable Name in For Loop Using R
Limit Ggplot2 Axes Without Removing Data (Outside Limits): Zoom
Consistent Width For Geom_Bar in the Event of Missing Data
Calculating Cumulative Sum For Each Row