我正在努力将数据转换为长格式
在 R 中,我有以下数据:
alcolevel <- c(0,0.5,1.5,4.0,7.0)
present <- c(48,38,5,1,0)
absent <- c(17066,14464,788,126,37)
dataset1 <- data.frame(alcolevel,present,absent)
alcolevel present absent
1 0 48 17066
2 0.5 38 14464
3 1.5 5 788
4 4.0 1 126
5 7.0 0 37
我希望将 dataset1 转换为:
alcolevel Y
0 present
0 present
0 absent
0 absent
0 absent
. .
. .
. .
0.5 absent
0.5 present
0.5 present
0.5 present
. .
. .
. .
1.5 present
. .
. .
. .
7.0 present
7.0 present
所以我得到 48 人在场,17066 人缺席 alcolevel 0
。其他同样alcolevel
类别。
转换后,新的长数据集将是一个长数据集。
我很感谢对这个问题的任何帮助。谢谢
最佳答案
如果我们需要复制,请在转为“长”格式后对“值”列进行uncount
library(dplyr)
library(tidyr)
dataset1 %>%
pivot_longer(cols = -alcolevel, names_to = 'Y' ) %>%
uncount(value) %>%
as_tibble
# A tibble: 32,573 x 2
# alcolevel Y
# <dbl> <chr>
# 1 0 present
# 2 0 present
# 3 0 present
# 4 0 present
# 5 0 present
# 6 0 present
# 7 0 present
# 8 0 present
# 9 0 present
#10 0 present
# … with 32,563 more rows
关于r - 将带有计数的宽数据帧转换为R中的长格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60195529/