【问题标题】:How to add new column to an dataframe (to the front not end)?如何将新列添加到数据框(到前端而不是末尾)?
【发布时间】:2013-10-30 18:08:33
【问题描述】:

如何将新变量添加到现有数据框中,但我想添加到前端而不是末尾。 例如。我的数据框是

b c d
1 2 3
1 2 3
1 2 3

我想添加一个新变量a,所以数据框看起来像

a b c d
0 1 2 3
0 1 2 3
0 1 2 3

【问题讨论】:

  • cbind(a = 0, df) 应该这样做。

标签: r dataframe


【解决方案1】:
df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
df
##   b c d
## 1 1 2 3
## 2 1 2 3
## 3 1 2 3

df <- data.frame(a = c(0, 0, 0), df)
df
##   a b c d
## 1 0 1 2 3
## 2 0 1 2 3
## 3 0 1 2 3

【讨论】:

  • 我觉得这比cbind好。
  • data.frame(a = 0, df) 就够了。
【解决方案2】:

使用cbind 例如

df <- data.frame(b = runif(6), c = rnorm(6))
cbind(a = 0, df)

给予:

> cbind(a = 0, df)
  a         b          c
1 0 0.5437436 -0.1374967
2 0 0.5634469 -1.0777253
3 0 0.9018029 -0.8749269
4 0 0.1649184 -0.4720979
5 0 0.6992595  0.6219001
6 0 0.6907937 -1.7416569

【讨论】:

    【解决方案3】:

    添加列“a”

    > df["a"] <- 0
    > df
      b c d a
    1 1 2 3 0
    2 1 2 3 0
    3 1 2 3 0
    

    使用列名按列排序

    > df <- df[c('a', 'b', 'c', 'd')]
    > df
      a b c d
    1 0 1 2 3
    2 0 1 2 3
    3 0 1 2 3
    

    或使用索引按列排序

    > df <- df[colnames(df)[c(4,1:3)]]
    > df
      a b c d
    1 0 1 2 3
    2 0 1 2 3
    3 0 1 2 3
    

    【讨论】:

    • 第二步:df[c("a", setdiff(names(df), "a"))] 更通用。
    【解决方案4】:

    前面的答案显示了 3 种方法

    1. 通过创建新数据框
    2. 通过使用“cbind”
    3. 通过添加列“a”,并使用列名或索引按列对数据帧进行排序

    让我展示 #4 方法“通过使用适用于我的案例的“cbind”和“rename”

    1。创建数据框

    df &lt;- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))

    2。获取“新”列的值

    new_column = c(0, 0, 0)

    3。将“新”列与现有列合并

    df &lt;- cbind(new_column, df)

    4。重命名“新”列名称

    colnames(df)[1] &lt;- "a"

    【讨论】:

    • 为什么要在上一个答案中添加步骤 XD ...如果您将所需名称的列分配作为参数传递df &lt;- cbind(a = 0), df)跨度>
    【解决方案5】:

    如果您想以tidyverse 的方式执行此操作,请尝试使用tibble 中的add_column,它允许您使用.before.after 参数指定放置新列的位置:

    library(tibble)
    
    df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
    add_column(df, a = 0, .before = 1)
    
    #   a b c d
    # 1 0 1 2 3
    # 2 0 1 2 3
    # 3 0 1 2 3
    

    【讨论】:

      【解决方案6】:

      cbind 按其参数顺序的固有顺序。

      将您的第一列用作您的第一个参数

      cbind(fst_col , df)

        fst_col   df_col1   df_col2
      1 0             0.2      -0.1
      2 0             0.2      -0.1
      3 0             0.2      -0.1
      4 0             0.2      -0.1
      5 0             0.2      -0.1
      

      cbind(df, last_col)

        df_col1   df_col2  last_col
      1 0.2      -0.1             0
      2 0.2      -0.1             0
      3 0.2      -0.1             0
      4 0.2      -0.1             0
      5 0.2      -0.1             0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-22
        • 2018-07-27
        • 1970-01-01
        • 2020-11-19
        • 2011-04-28
        • 2021-06-27
        • 2020-03-15
        相关资源
        最近更新 更多