【问题标题】:Flatting a dataframe with all values of a column into one将具有列的所有值的数据框扁平化为一个
【发布时间】:2015-12-19 07:52:02
【问题描述】:

我有一个这种格式的数据框

str(df2)
'data.frame':   2 obs. of  10 variables:
 $ stc1 : Factor w/ 2 levels "price_of_A_stock",..: 1 2
 $ stc2 : Factor w/ 2 levels "price_of_B_stock",..: 1 2
 $ stc3 : Factor w/ 2 levels "price_of_C_stock",..: 1 2

我想让它把每一列的所有值合为一个,而不用列名

为了做到这一点,我使用了这个:

r_df <- as.data.frame(t(df2))

但我得到的结果是这样的:

str(r_df)
'data.frame':   10 obs. of  2 variables:
 $ 1: Factor w/ 10 levels "price_of_A_stock",..: 3 6 8 1 5 9 10 7 4 2
  ..- attr(*, "names")= chr  "stc1" "stc2" "stc3" "stc4" ...
 $ 2: Factor w/ 10 levels "price_of_B_stock",..: 7 9 10 6 1 8 4 3 2 5
  ..- attr(*, "names")= chr  "stc1" "stc2" "stc3" "stc4" ...

【问题讨论】:

  • 我不知道如何重新创建您的数据框。您能否将其包含在您的问题中,可能使用dput?
  • 您能否添加一个示例,结果应该是怎样的?

标签: r


【解决方案1】:

我们可以使用unlist

data.frame(Col1= unlist(df2, use.names=FALSE))

【讨论】:

    【解决方案2】:

    你也可以使用 reshape2 包中的 melt() 函数,例如

    library(reshape2)
    r_df<-as.data.frame(melt(df2)$value)
    

    【讨论】:

      【解决方案3】:

      您也可以使用unname 和unlist。

      unname(unlist(df2))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-10
        • 1970-01-01
        • 2019-04-23
        相关资源
        最近更新 更多