【问题标题】:r: split column into multiple columns by value [duplicate]r:按值将列拆分为多列[重复]
【发布时间】:2013-12-03 15:17:53
【问题描述】:

我有一个这样的数据框:

df <- data.frame(first = rep(c("A","B","C","D","E")), second = rep(c(1,2),each=5), 
                 third = rnorm(10))

.

> df
   first second       third
1      A      1 -0.47175662
2      B      1  0.92905470
3      C      1 -0.79385274
4      D      1  0.68175904
5      E      1 -0.91112323
6      A      2  0.24941514
7      B      2 -0.74557229
8      C      2  0.92419408
9      D      2  0.34787484
10     E      2 -0.04578459

我想根据列的值将“第二”列拆分为 2 列(对应于第二列中值 1 的第三列的值将形成第 1 列)。所以我会得到:

    first    1        2
1   A   -0.47175662 0.24941514
2   B   0.9290547   -0.74557229
3   C   -0.79385274 0.92419408
4   D   0.68175904  0.34787484
5   E   -0.91112323 -0.04578459

我查看了 reshape 包,但不知道该怎么做。我能够使用 xtabs 获得看起来像这样的表格,但我需要在数据框中使用它,而不是在表格中。

【问题讨论】:

  • wide 方向尝试reshape

标签: r reshape


【解决方案1】:
set.seed(1)
df <- data.frame(first = rep(c("A","B","C","D","E")), second = rep(c(1,2),each=5), 
                  third = rnorm(10))
library(reshape2)
dcast(df, first ~ second)

#Using third as value column: use value.var to override.
#  first          1          2
#1     A -0.6264538 -0.8204684
#2     B  0.1836433  0.4874291
#3     C -0.8356286  0.7383247
#4     D  1.5952808  0.5757814
#5     E  0.3295078 -0.3053884

【讨论】:

    【解决方案2】:

    好的,抱歉,我找到了方法:

    dcast(df, first ~ second, value.var="third")
    

    【讨论】:

      【解决方案3】:

      在答案中制定 Metrics 的评论:

      reshape(df, direction = "wide", idvar="first", timevar="second")
      #   first     third.1     third.2
      # 1     A  0.71266631  0.06016044
      # 2     B -0.07356440 -0.58889449
      # 3     C -0.03763417  0.53149619
      # 4     D -0.68166048 -1.51839408
      # 5     E -0.32427027  0.30655786
      

      【讨论】:

        猜你喜欢
        • 2021-09-21
        • 2017-11-08
        • 2014-07-28
        • 2017-03-28
        • 1970-01-01
        • 2017-12-16
        • 2021-12-28
        • 2019-07-06
        • 1970-01-01
        相关资源
        最近更新 更多