按顺序确定变化的强度和位置

时间:2014-11-15 17:24:20

标签: r dataframe sequence

假设我有一个表格,其中行包含对象的测量值(" A"," B"," C"," D" )随着时间的推移(t1到t5)。

mat <- as.data.frame(matrix(c(0,0,0,3,0,0,3,0,0,0,
                              1,0,0,0,0,0,0,0,0,1),
                     nrow = c(4,5), byrow=TRUE))
colnames(mat) <- c("t1","t2","t3","t4","t5")
rownames(mat) <- c("A","B","C","D"); mat

表格如下:

  t1 t2 t3 t4 t5
A  0  0  0  3  0
B  0  3  0  0  0
C  1  0  0  0  0
D  0  0  0  0  1

如何生成两个新列 - 一个包含最大值,另一个包含具有该值的列名称

我应该是这样的:

  t1 t2 t3 t4 t5  strength  time
A  0  0  0  3  0         3    t4
B  0  3  0  0  0         3    t2
C  1  0  0  0  0         1    t1
D  0  0  0  0  1         1    t5

我希望这是足够可重复的例子。

1 个答案:

答案 0 :(得分:2)

尝试

indx <- max.col(mat) 
cbind(mat, strength=mat[cbind(1:nrow(mat), indx)],
                  time=names(mat)[indx])

#   t1 t2 t3 t4 t5 strength time
#A  0  0  0  3  0        3   t4
#B  0  3  0  0  0        3   t2
#C  1  0  0  0  0        1   t1
#D  0  0  0  0  1        1   t5