r - 转换有序数据

标签 r

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

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/

相关文章:

r - 有在R窗口中显示文本的功能吗?

r - 识别在 x 天内发生给定事件序列的记录

r - 输出PDF时如何将Bookdown中的二级表头左对齐?

r - 将 xtable 中底行的内容加粗

r - 如何在一个图中绘制 'multiple box plots'?

R图例不起作用

r - 如何根据条件将字符串的特定数字替换为另一个值

r - 如何使用控制台输出捕获警告?

xml - R XML - 尝试将节点添加到内部节点时出错

r - 如何确保 spatstat::owin(poly=<polygon>) 中的多边形没有 "negative area"