在R中重新变换为长整数并包括序列号

时间:2022-02-21 04:29:18

I am looking to take data that is currently wide and melt it into a long format. The trick is that I want to create a sequence indicator.

我希望获取目前广泛的数据并将其融合为长格式。诀窍是我想创建一个序列指示器。

Here are my data:

这是我的数据:

df.wide <- data.frame(id = 1:5, 
                      code1 = sample(month.abb, 5),
                      code2 = sample(month.abb, 5))

What I am looking for:

我在找什么:

   id rank value
1   1    1       Dec
2   1    2       Jan
3   2    1       May
4   2    2       Jun
5   3    1       Aug
6   3    2       Aug
7   4    1       Sep
8   4    2       Mar
9   5    1       Dec
10  5    2       Nov

I suspect that I could use this:

我怀疑我可以用这个:

melt(df.wide, id=c("id"))

and iterate over the data aftewards to clean up the results, but I know reshape is a great package and wanted to ask before I reinvent the wheel.

然后迭代数据以清理结果,但我知道重塑是一个很棒的包,我想在重新发明*之前询问。

2 个解决方案

#1


4  

Here is a one-liner using the reshape function in base R (not to be confused with the reshape package)

这是使用基础R中的重塑功能的单行(不要与重塑包混淆)

reshape(df.wide, varying = 2:3, timevar = 'rank', sep = "", direction = 'long')

#2


2  

As far as I know, you're on track.

据我所知,你正在走上正轨。

df.melt <- melt(df.wide, idvar='id', variable_name='rank')
df.melt$rank <- gsub('code', '', df.melt$rank)

No need to iterate per say.

无需按照说法进行迭代。

You could also use:

你也可以使用:

levels(df.melt$rank) <- 1:2

But, notice both versions give characters rather than numbers. wrap the gsub in as.numeric() if you need numbers.

但是,请注意两个版本都提供字符而不是数字。如果需要数字,请将as包含在as.numeric()中。

#1


4  

Here is a one-liner using the reshape function in base R (not to be confused with the reshape package)

这是使用基础R中的重塑功能的单行(不要与重塑包混淆)

reshape(df.wide, varying = 2:3, timevar = 'rank', sep = "", direction = 'long')

#2


2  

As far as I know, you're on track.

据我所知,你正在走上正轨。

df.melt <- melt(df.wide, idvar='id', variable_name='rank')
df.melt$rank <- gsub('code', '', df.melt$rank)

No need to iterate per say.

无需按照说法进行迭代。

You could also use:

你也可以使用:

levels(df.melt$rank) <- 1:2

But, notice both versions give characters rather than numbers. wrap the gsub in as.numeric() if you need numbers.

但是,请注意两个版本都提供字符而不是数字。如果需要数字,请将as包含在as.numeric()中。