Learn R Programming

EDCimport (version 0.6.0)

unify: Unify a vector

Description

Turn a vector of length N to a vector of length 1 after checking that there is only one unique value. Useful to safely flatten a duplicated table. Preserves the label attribute if set.

Usage

unify(x, collapse_chr = FALSE, warn = TRUE)

Value

a vector of length 1

Arguments

x

a vector

collapse_chr

whether to collapse non-unique character values

warn

whether to warn if non-unique values were found

Examples

Run this code
unify(c(1,1,1,1))
#unify(c(1,1,2,1)) #warning

library(dplyr)
set.seed(42)
x=tibble(id=rep(letters[1:5],10), value=rep(1:5,10), 
         value2=sample(letters[6:10], 50, replace=TRUE))
x %>% summarise(value=unify(value), .by=id) #safer than `value=value[1]`
x %>% summarise(value2=unify(value2, collapse_chr=TRUE, warn=FALSE), .by=id)
x$value[2]=1
x %>% summarise(value2=unify(value2), .by=id) #warning about that non-unique value

Run the code above in your browser using DataLab