split divides the data in the vector x into the groups defined by f. The replacement forms replace values corresponding to such a division. unsplit reverses the effect of split.
split(x, f, drop = FALSE, …)
# S3 method for default
split(x, f, drop = FALSE, sep = ".", lex.order = FALSE, …)<p></p><p>split(x, f, drop = FALSE, …) <- value
unsplit(value, f, drop = FALSE)</p>
| Parameter | Description |
|---|---|
x |
vector or data frame containing values to be divided into groups. |
f |
a ‘factor’ in the sense that as.factor(f) defines the grouping, or a list of such factors in which case their interaction is used for the grouping. |
drop |
logical indicating if levels that do not occur should be dropped (if f is a factor or a list). |
value |
a list of vectors or data frames compatible with a splitting of x. Recycling applies if the lengths do not match. |
sep |
character string, passed to interaction in the case where f is a list. |
lex.order |
logical, passed to interaction when f is a list. |
… |
further potential arguments passed to methods. |
# NOT RUN {
require(stats); require(graphics)
n <- 10; nn <- 100
g <- factor(round(n * runif(n * nn)))
x <- rnorm(n * nn) + sqrt(as.numeric(g))
xg <- split(x, g)
boxplot(xg, col = "lavender", notch = TRUE, varwidth = TRUE)
sapply(xg, length)
sapply(xg, mean)
### Calculate 'z-scores' by group (standardize to mean zero, variance one)
z <- unsplit(lapply(split(x, g), scale), g)
# or
zz <- x
split(zz, g) <- lapply(split(x, g), scale)
# and check that the within-group std dev is indeed one
tapply(z, g, sd)
tapply(zz, g, sd)
### data frame variation
## Notice that assignment form is not used since a variable is being added
g <- airquality$Month
l <- split(airquality, g)
l <- lapply(l, transform, Oz.Z = scale(Ozone))
aq2 <- unsplit(l, g)
head(aq2)
with(aq2, tapply(Oz.Z, Month, sd, na.rm = TRUE))
### Split a matrix into a list by columns
ma <- cbind(x = 1:10, y = (-4:5)^2)
split(ma, col(ma))
split(1:10, 1:2)
# }