R中带有数字条目的熔化函数

Melt function with numerical entries in R

我对 R 中的 melt 函数有以下问题(它是 reshape2 包的一部分)。

假设我有以下示例:

library(reshape2)
# I start with a matrix and create a data frame 
# who's first column is a numbering of the rows.
HH <- matrix(0, nrow = 10, ncol = 20)
df <- data.frame( pp = 1:10, HH)
# Then I melt it using the row number as a pivot (or id).
df <- melt(df ,  id.vars = 'pp', variable.name = 'time')

我得到的是正确类型的矩阵,但是 "Time" 数据包含类型 x1, ... , x2 的元素,我真的很想要数值供以后使用(比如 1,...,2)。我想一定有一些非常聪明的方法可以实现这一点,而不是编写更改所有条目名称的代码。

这可能是 "tidyverse" 可以提供帮助的情况,特别是通过在 gather 中使用 convert 参数。我还通过在 data.frame(...) 步骤中添加 check.names = FALSE 来更改创建 data.frame 的方式。但是请注意,使用该方法您最终会得到语法上无效的名称,但由于您的目标数据集结构不同,所以这无关紧要。

示例:

library(tidyverse)
df <- data.frame(pp = 1:10, HH, check.names = FALSE)
gather(df, key, value, -pp, convert = TRUE)

str(gather(df, key, value, -pp, convert = TRUE))
# 'data.frame': 200 obs. of  3 variables:
#  $ pp   : int  1 2 3 4 5 6 7 8 9 10 ...
#  $ key  : int  1 1 1 1 1 1 1 1 1 1 ...
#  $ value: num  0 0 0 0 0 0 0 0 0 0 ...