katarado
katarado

Reputation: 37

Vector of Counts in R

This is my table

booksRead 0 1 2 3 4 5 6 7 8 9

frequency 2 4 4 8 4 5 2 4 2 1

With frequency being the number of students having read x books for example. eg, 8 students read 3 books last week

Created with

> nTimes <- c(0:9)
> frequency <-c(2,4,4,8,4,5,2,4,2,1)
> xTable <- rbind(nTimes,frequency)

I want to find a way to get

vectorOfCounts <- c(0,0,1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5,5,6,6,7,7,7,7,8,8,9)

without having to type it. Ideally, I would somehow use the variable I created previously.

Upvotes: 1

Views: 96

Answers (2)

d.b
d.b

Reputation: 32538

Use rep

DATA

booksRead = c( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
frequency= c(2, 4, 4, 8, 4, 5, 2, 4, 2, 1)

COMMAND

vectorOfCounts = rep(x = booksRead,times = frequency)
vectorOfCounts
# [1] 0 0 1 1 1 1 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 5 5 5 5 5 6 6 7 7 7 7 8 8 9

Upvotes: 2

David C.
David C.

Reputation: 1994

You can achieve it iteratively, by using a for-loop:

booksRead <- 0:9
frequency <- c(2, 4, 4, 8, 4, 5, 2, 4, 2, 1)

length(booksRead) == length(frequency) #check: TRUE required

Counts <- c() #initialize by empty vector
for(i in 1:length(booksRead)) {
  Counts <- c(Counts, rep(booksRead[i], frequency[i]))
} #update iteratively

Counts

## [1] 0 0 1 1 1 1 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 5 5 5 5 5 6 6 7 7 7
## [33] 7 8 8 9

Upvotes: -1

Related Questions