【问题标题】:Pivoting dataframe cols to rows based on logical condition on values [duplicate]根据值的逻辑条件将数据框列旋转到行[重复]
【发布时间】:2018-07-17 07:40:36
【问题描述】:

我在 R 中有一个数据框,它有(例如)10 行和 10 列。数据框中的值将是 0 或 1。

例如

1 0 0 1 0 0 0 0 1 1
0 1 0 1 0 1 0 1 0 1 
...

现在我想以这种格式将此数据输出到一个新文件中

1 1
1 4
1 9
1 10
2 2
2 4
2 6
2 8
2 10
....

这里的输出格式是(行索引,列索引),其中值为1。

我在“for”循环中执行此操作,但处理速度太慢。是否有任何向量/矩阵运算或其他可以更快完成的包?

提前致谢。

【问题讨论】:

标签: r dataframe subset


【解决方案1】:

你可以使用apply函数:

## For the following matrix
df <- matrix(sample(c(0,1), 25, replace = TRUE), 5, 5)
df
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    0    1    0    0    0
# [2,]    0    1    0    1    1
# [3,]    0    0    0    0    0
# [4,]    0    0    1    1    1
# [5,]    1    0    0    1    1

## The positions of the "1" in the columns
col <- apply(df, 1, function(X) which(X == 1))
## The number of "1" per rows
rows1 <- lapply(col, length)
rows2 <- lapply(as.list(1:length(rows1)), function(X, rows1) rep(X, rows1[[X]]), rows1)

## Combining both
cbind(unlist(rows2), unlist(col))

#      [,1] [,2]
# [1,]    1    2
# [2,]    2    2
# [3,]    2    4
# [4,]    2    5
# [5,]    4    3
# [6,]    4    4
# [7,]    4    5
# [8,]    5    1
# [9,]    5    4
#[10,]    5    5

【讨论】:

  • 这可行,但 which 已经有一个 arr.ind= 参数可以完成所有这些繁重的工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-17
  • 2023-03-03
  • 1970-01-01
  • 2016-04-16
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
相关资源
最近更新 更多