【问题标题】:Long to wide with duplicate row names [duplicate]长到宽,行名重复[重复]
【发布时间】:2017-06-23 10:40:18
【问题描述】:

我认为这个特定问题以前没有出现在论坛上,但如果是重复的问题,请指出正确的方向!

我有以下数据集,想将其从长变宽。

ID   variable                   value
1   number of students          1000
1   percentage on financial aid  28
1   acceptance rate              12
1   percentage on financial aid  35
2   number of students          2000
2   percentage on financial aid  1
2   percentage on financial aid  70

请注意,percentage on financial aid 的值对于每个 id 出现两次。当从长到宽时,我想只保留第二次出现,因为第一次出现的是“经济援助”衡量的学校排名,而第二次出现的是实际值。

变量名percentage on financial aid 对这两个值完全相同,所以我想知道是否有办法告诉R 用第二个覆盖第一个出现。现在 R 似乎保留了第一次出现。

【问题讨论】:

  • 正如你所说,你只想拿最后一次出现为 dups。为什么不先过滤它们?
  • First occurence 你的意思是随机的吧?
  • 啊,你是对的@mt1022。我忘记了我可以做 fromLast=TRUE 并保留第二个实例。非常感谢!

标签: r reshape reshape2


【解决方案1】:
zz = '
ID   variable                   value
1   number_of_students          1000
1   percentage_on_financial_aid  28
1   acceptance_rate              12
1   percentage_on_financial_aid  35
2   number_of_students          2000
2   percentage_on_financial_aid  1
2   percentage_on_financial_aid  70
'

df <- read.table(text = zz, header = TRUE)


ndf = apply(df, 2, rev)
ndf = as.data.frame(ndf)
nd = reshape(ndf, idvar = "ID", timevar = "variable", direction = "wide")
a = colnames(nd)
b = sub('.*\\.', '', a)
colnames(nd) = b
nd

  ID percentage_on_financial_aid number_of_students acceptance_rate
1  2                          70               2000            <NA>
4  1                          35               1000              12

如果你选择fromLast = T 那么:

nd = reshape(df, idvar = "ID", timevar = "variable", direction = "wide")
a = colnames(nd)
b = sub('.*\\.', '', a)
colnames(nd) = b
nd

【讨论】:

    【解决方案2】:

    多亏了评论的人,我才明白这一点。

    解决方案:

    df &lt;- subset(df,duplicated(df[,1:2])|!duplicated(df[,1:2],fromLast=TRUE))

    【讨论】:

      猜你喜欢
      • 2016-09-23
      • 1970-01-01
      • 2021-04-30
      • 2020-05-18
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      相关资源
      最近更新 更多