Learn R Programming

splitstackshape (version 1.4.8.1)

expandRows: Expand the Rows of a Dataset

Description

Expands (replicates) the rows of a data.frame or data.table, either by a fixed number, a specified vector, or a value contained in one of the columns in the source data.frame or data.table.

Usage

expandRows(dataset, count, count.is.col = TRUE, drop = TRUE)

Value

A data.frame or data.table, depending on the input.

Arguments

dataset

The input data.frame or data.table.

count

The numeric vector of counts OR the column from the dataset that contains the count data. If count is a single digit, it is assumed that all rows should be repeated by this amount.

count.is.col

Logical. Is the count value a column from the input dataset? Defaults to TRUE.

drop

Logical. If count.is.col = TRUE, should the "count" column be dropped from the result? Defaults to TRUE.

Author

Ananda Mahto

References

http://stackoverflow.com/a/19519828/1270695

Examples

Run this code

mydf <- data.frame(x = c("a", "b", "q"), 
                   y = c("c", "d", "r"), 
                   count = c(2, 5, 3))
library(data.table)
DT <- as.data.table(mydf)
mydf
expandRows(mydf, "count")
expandRows(DT, "count", drop = FALSE)
expandRows(mydf, count = 3) ## This takes values from the third column!
expandRows(mydf, count = 3, count.is.col = FALSE)
expandRows(mydf, count = c(1, 5, 9), count.is.col = FALSE)
expandRows(DT, count = c(1, 5, 9), count.is.col = FALSE)

Run the code above in your browser using DataLab