下图是数据集的表示。我尝试使用reshape和ivot_wider来扩大数据,但无法以我期望的方式获得结果。我尝试从堆栈溢出中将多行合并为单行,但发现解决方案是错误的。
随机数据集生成的代码:
df1 <- data.frame(Components = c(rep("ABC",5),rep("BCD",5)),
Size = c(sample(1:100,5),sample(45:100,5)),
Age = c(sample(1:100,5),sample(45:100,5)))
尝试此tidyverse
解决方案,它将产生接近您想要的输出。您可以分组依据,Components
然后创建一个顺序ID,以标识将来的列。重塑为long(pivot_longer()
)之后,将变量名与id合并,然后重塑为wide(pivot_wider()
)。这是我使用您共享数据的代码:
library(tidyverse)
#Code
newdf <- df1 %>% group_by(Components) %>% mutate(id=row_number()) %>%
pivot_longer(-c(Components,id)) %>%
mutate(name=paste0(name,'.',id)) %>% select(-id) %>%
pivot_wider(names_from = name,values_from=value)
输出:
# A tibble: 2 x 11
# Groups: Components [2]
Components Size.1 Age.1 Size.2 Age.2 Size.3 Age.3 Size.4 Age.4 Size.5 Age.5
<fct> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
1 ABC 23 94 52 89 15 25 76 38 33 99
2 BCD 59 62 55 81 81 61 80 83 97 68
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句