gpt4 book ai didi

r - 转换有序数据

转载 作者:行者123 更新时间:2023-12-01 08:50:20 25 4
gpt4 key购买 nike

我已经设法获取了以下格式的数据:

run    type1
data1 12
data2 13
run type2
data1 14
data2 15
...

我要:

run    data1 data2
type1 12 13
type2 14 15
...

我试过 cast/dcast 都无济于事。有什么建议吗?

示例数据:

data.frame(matrix(c("run","type1","data1",12,"data2",13,"run","type2","data1",14,"data3",15), ncol=2, byrow=T))

最佳答案

这是我的建议:

cast.runs <- function(d) {
isrun <- d[[1]]=="run"
whichrun <- which(isrun)
lens <- diff(c(whichrun, nrow(d)+1))
runlabels <- inverse.rle(list(lengths=lens, values=d[[2]][whichrun]))
return(cbind(run=runlabels, d)[!isrun,])
}

此函数将生成合适的长格式,然后您可以根据需要重新转换:

  runlabels    X1 X2
2 type1 data1 12
3 type1 data2 13
5 type2 data1 14
6 type2 data3 15

不出所料,我首先确定 run 行。我计算了每次运行有多少行,包括标题行。该代码的灵感来自 this answer .接下来,我多次重复每个运行标签,最后删除标题行。

转换此输出的一种可能方法是使用 reshape2 包中的 dcast 函数:

> dcast(cast.runs(d), run ~ X1)
Using X2 as value column: use value.var to override.
run data1 data2 data3
1 type1 12 13 <NA>
2 type2 14 <NA> 15

关于r - 转换有序数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24637921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com