在R中强制转换(旋转)之前的唯一值 [英] Forcing unique values before casting (pivoting) in R

查看:15
本文介绍了在R中强制转换(旋转)之前的唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,如下所示

Identifier  V1  Location    V2
1   12  A   21
1   12  B   24
2   20  B   15
2   20  C   18
2   20  B   23
3   43  A   10
3   43  B   17
3   43  A   18
3   43  B   20
3   43  C   25
3   43  A   30

我想重新转换它,在Current Location列中,每个标识符占一行,每个值占一列。我不关心V1中的数据,但我需要V2中的数据,这些数据将成为新列中的值。

请注意,对于Location列,标识符2和3有重复值。

我假设第一个任务是使Location列中的值是唯一的。

我使用了以下内容(数据框称为"测试")

L<-length(Test$Identifier)
for (i in 1:L) 
{
temp<-Test$Location[Test$Identifier==i]
temp1<-make.unique(as.character(temp), sep="-")
levels(Test$Location)=c(levels(Test$Location),temp1)
Test$Location[Test$Identifier==i]=temp1
}

这会产生

Identifier  V1  Location    V2
1   12  A   21
1   12  B   24
2   20  B   15
2   20  C   18
2   20  B-1 23
3   43  A   10
3   43  B   17
3   43  A-1 18
3   43  B-1 20
3   43  C   25
3   50  A-2 30

然后使用

cast(Test, Identifier ~ Location)

给予

Identifier  A   B   C   B-1 A-1 A-2
1   21  24  NA  NA  NA  NA
2   NA  15  18  23  NA  NA
3   10  17  25  20  18  30

这或多或少就是我想要的。

我的问题是

这是处理问题的正确方法吗?

我知道R-人们不使用"for"结构,那么有没有更优雅的R-呢?这是怎么做的?值得一提的是,实际数据集有160,000多行,从位置向量中的50多个唯一值开始,该函数只需要一个小时多一点的时间就可以运行。任何快一点的都是好的。我还应该提到,尽管增加了内存限制,CAST函数仍必须一次在20-30K的输出行上运行。然后合并所有CAST输出

有没有办法将输出中的列排序为A、A-1、A-2、B、B-1、C

请温文尔雅地回复!

推荐答案

作为参考,这里是@Roland在基数R中的等价物

使用ave创建唯一的"Location"列...

DF$Location <- with(DF, ave(Location, Identifier, 
                    FUN = function(x) make.unique(x, sep = "-")))

.和reshape更改数据结构。

## If you want both V1 and V2 in your "wide" dataset
## "dcast" can't directly do this--you'll need `recast` if you 
##    wanted both columns, which first `melt`s and then `dcast`s....
reshape(DF, direction = "wide", idvar = "Identifier", timevar = "Location")

## If you only want V2, as you indicate in your question
reshape(DF, direction = "wide", idvar = "Identifier", 
        timevar = "Location", drop = "V1")
#   Identifier V2.A V2.B V2.C V2.B-1 V2.A-1 V2.A-2
# 1          1   21   24   NA     NA     NA     NA
# 3          2   NA   15   18     23     NA     NA
# 6          3   10   17   25     20     18     30

可以按照@Roland建议的方式对列进行重新排序。

这篇关于在R中强制转换(旋转)之前的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆