base spread mimics basic functionality of tidyr::spread

b_spread(data, key, value, convert = FALSE)

Arguments

data

data.frame

key

column which will become the new columns

value

column name which will populate new columns

convert

type.convert will run on each result column if TRUE, Default: FALSE

Value

data.frame

Examples

stocks <- data.frame( time = as.Date('2009-01-01') + 0:9, X = rnorm(10, 0, 1), Y = rnorm(10, 0, 2), Z = rnorm(10, 0, 4) ) stocksm <- b_gather(stocks,'stock', 'price', -1) b_spread(stocksm, 'stock', 'price')
#> time X Y Z #> 1 2009-01-01 -1.400043517 -1.1073988 1.87261768 #> 2 2009-01-02 0.255317055 1.2579641 1.45180502 #> 3 2009-01-03 -2.437263611 4.1300498 -5.21817418 #> 4 2009-01-04 -0.005571287 -3.2619788 2.95110529 #> 5 2009-01-05 0.621552721 1.0248539 7.55401972 #> 6 2009-01-06 1.148411606 -3.7260230 -0.38978042 #> 7 2009-01-07 -1.821817661 -1.0440250 -3.74338941 #> 8 2009-01-08 -0.247325302 -0.1052038 -0.06380125 #> 9 2009-01-09 -0.244199607 1.0859927 -3.30715581 #> 10 2009-01-10 -0.282705449 -1.8281497 -6.04959861
# spread and gather are complements df <- data.frame(x = c("a", "b"), y = c(3, 4), z = c(5, 6)) sdf <- b_spread(df, 'x', 'y') b_gather(sdf, 'x', 'y', -1, na.rm = TRUE)
#> z x y #> 1 5 a 3 #> 4 6 b 4
# Use 'convert = TRUE' to produce variables of mixed type df <- data.frame(row = rep(c(1, 51), each = 3), var = c("Sepal.Length", "Species", "Species_num"), value = c(5.1, "setosa", 1, 7.0, "versicolor", 2)) str(b_spread(df, 'var', 'value'))
#> 'data.frame': 2 obs. of 4 variables: #> $ row : num 1 51 #> $ Sepal.Length: Factor w/ 6 levels "1","2","5.1",..: 3 4 #> $ Species : Factor w/ 6 levels "1","2","5.1",..: 5 6 #> $ Species_num : Factor w/ 6 levels "1","2","5.1",..: 1 2
str(b_spread(df, 'var', 'value',convert = TRUE))
#> 'data.frame': 2 obs. of 4 variables: #> $ row : num 1 51 #> $ Sepal.Length: num 3 4 #> $ Species : chr "setosa" "versicolor" #> $ Species_num : num 1 2