看起来tidyr
现在可以自动识别它 - 它可以两种方式工作:输入列名或将它们放入字符串中
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 <- stocks %>% gather(stock, price, -time) # make it to skinny table
# make it wide table
stocksm %>% spread(stock, price)
# time X Y Z
# 1 2009-01-01 0.7444343 -0.07030219 0.9140019
# 2 2009-01-02 1.1988507 2.98659296 5.3044361
# 3 2009-01-03 -0.4344259 -0.11526884 -3.8380602
# 4 2009-01-04 0.8154400 2.08313458 -0.1152524
# 5 2009-01-05 1.1965647 -0.59055846 3.5647410
# ...
# it's same if put column names in strings
stocksm %>% spread('stock', 'price')
# time X Y Z
# 1 2009-01-01 0.7444343 -0.07030219 0.9140019
# 2 2009-01-02 1.1988507 2.98659296 5.3044361
# 3 2009-01-03 -0.4344259 -0.11526884 -3.8380602
# 4 2009-01-04 0.8154400 2.08313458 -0.1152524
# 5 2009-01-05 1.1965647 -0.59055846 3.5647410
# or put in string variables
col1 = 'stock'
col2 = 'price'
stocksm %>% spread(col1, col2)
# time X Y Z
# 1 2009-01-01 0.7444343 -0.07030219 0.9140019
# 2 2009-01-02 1.1988507 2.98659296 5.3044361
# 3 2009-01-03 -0.4344259 -0.11526884 -3.8380602
# 4 2009-01-04 0.8154400 2.08313458 -0.1152524
# 5 2009-01-05 1.1965647 -0.59055846 3.5647410