【问题标题】:Use spread with three columns where first column has state and second transition state and values in third对三列使用展开,其中第一列具有状态,第二列具有过渡状态,值位于第三列
【发布时间】:2015-12-11 15:30:42
【问题描述】:

我有这样的输入。

type1   type2   2
type1   type3   4
type1   type5   3
type2   type1   6
type2   type4   2
type2   type3   3
type3   type1   2
type3   type2   2
type3   type4   4
type4   type1   7
type4   type2   1
type4   type3   4
type5   type1   2
type5   type3   3
type5   type4   1

这里第一列是假设一个状态,第二列是第二个状态,第三列有对应于这个转换的值。所以我希望它被传播,这样我在 column1 中有唯一的状态,其余的列是具有所有唯一列名的名称,并且行中的每个单元格都应该包含第三列的计数。

所以输出应该是这样的。

types   type1   type2   type3   type4   type5
type1   0       2       4       0       3
type2   6       0       3       2       0
type3   2       2       0       2       0
type4   7       1       4       0       0
type5   2       0       3       1       0

我试过这个,它给出了错误:行 (7, 8) 的标识符重复。我不知道在这种情况下如何使用传播。

seq=read.csv("test.txt",header=FALSE,sep="\t")
colnames(seq) = c("state1","state2","counts")
seqs=spread(data=seq,state1,state2,fill=0)

感谢任何帮助。

【问题讨论】:

  • 你几乎拥有它。试试spread(seq, state2, counts, fill = 0)
  • xtabs(counts~., df)
  • @docendo discimus 。我之前尝试过并更新了我的帖子,但它出错了,因为它不适用于不同的更大数据。

标签: r


【解决方案1】:

与此类似的问题:Rearrange dataframe to a table, the opposite of "melt"

reshape2::dcast 函数运行良好。

例子:

ColA <- rep(c('a', 'b', 'c'), each=3)
ColB <- rep(c('a', 'b', 'c'), times=3)
ColC <- round(runif(9)*10, 0)
df <- data.frame(ColA, ColB, ColC)
require(reshape2)
dcast(df, ColA~ColB)

输出:

  ColA a b c
1    a 8 3 4
2    b 7 8 6
3    c 9 5 8

【讨论】:

    【解决方案2】:

    reshape2 的解决方案很简单:

    dcast(df, V1 ~ V2, fill=0)
    #     V1 type1 type2 type3 type4 type5
    #1 type1     0     2     4     0     3
    #2 type2     6     0     3     2     0
    #3 type3     2     2     0     4     0
    #4 type4     7     1     4     0     0
    #5 type5     2     0     3     1     0
    

    【讨论】:

      【解决方案3】:

      我认为下面的代码会为你解决这个问题:

      > grid <- with(d, expand.grid(V1=levels(V1), V2=levels(V2)))
      > d2 <- merge(d, grid, all.y=TRUE)
      > l <- split(d2[c("V2", "V3")], d2$V1)
      > t(sapply(l, function(x) { ret <- x$V3; names(ret) <- x$V2; ret}))
            type1 type2 type3 type4 type5
      type1    NA     2     4    NA     3
      type2     6    NA     3     2    NA
      type3     2     2    NA     4    NA
      type4     7     1     4    NA    NA
      type5     2    NA     3     1    NA
      

      可能不是执行此操作的最好看的代码,但这是我想到的。

      【讨论】:

      • 这行得通。我想出的是错误的。当我添加更多数据时它没有工作。
      • 虽然这行得通,但考虑到这个常见的重塑问题有很多更简单的解决方案,我不推荐它。
      • 我同意,在这种情况下 dcast() 很可能是更好的解决方案。
      猜你喜欢
      • 2016-08-06
      • 2021-01-27
      • 2016-04-25
      • 1970-01-01
      • 1970-01-01
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多