我想重新排列我的数据,这里有一个例子来说明--我希望有一个简单的方法来改变tibble形成矩阵。这里有一个例子来说明--我希望有一个简单的方法来改变tibble来形成矩阵。矩阵也可以是一个tibble,尽管我想添加 "年份 "作为因子(第六列)。理想的情况是,你能够反过来。
library(tidyverse)
set.seed(112)
n <- sample(3:36, 15, replace = T)
year <- rep(2000:2002, 5)
lic <- rep(c("imp", "proc", "rec", "whl", "ret"), 3)
d1 <- as_tibble(cbind(year, lic, n))
colnames(d1) <- c("year", "license", "n")
d1 <- d1 %>%
mutate(year = as.integer(year), license = as.character(license), n = as.numeric(n))
set.seed(112)
d2 <- matrix(sample(3:36, 15, replace = T), ncol = 5, byrow = T)
colnames(d2) <- c("imp", "proc", "rec", "whl", "ret")
rownames(d2) <- c(2000:2002)
我希望能够将 d1 转换为 d2,理想情况下,可以用类似于矩阵转置的方式,使用 t()
.
谢谢你
你可以使用 pivot_wider()
从tidyr,值与枢轴宽提供与 values_from=
而他们将被命名为 names_from=
:
pivot_wider(d1,names_from=license,values_from=n)
# A tibble: 3 x 6
year imp proc rec whl ret
<int> <dbl> <dbl> <dbl> <dbl> <dbl>
1 2000 12 35 31 26 4
2 2001 35 8 24 7 34
3 2002 33 33 34 8 17
或者如果你喜欢好的老基数R,但这只在以下情况下有效 year
和 license
是因素。
do.call(rbind,by(d1,d1$year,function(i)tapply(i$n,i$license,identity)))
imp proc rec whl ret
2000 12 8 34 26 34
2001 33 35 24 8 4
2002 35 33 31 7 17
你可以用 spread
从 tidyr
包来做这件事
spread(d1, key = license, value = n)
# A tibble: 3 x 6
year imp proc rec ret whl
<int> <dbl> <dbl> <dbl> <dbl> <dbl>
1 2000 12 35 31 4 26
2 2001 35 8 24 34 7
3 2002 33 33 34 17 8