How to add new column to an dataframe (to the front not end)?

后端 未结 6 1577
情深已故
情深已故 2020-11-30 23:55

How to add a new variable to an existing data frame, but I want to add to the front not end. eg. my dataframe is

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

I

6条回答
  •  -上瘾入骨i
    2020-12-01 00:43

    The previous answers show 3 approaches

    1. By creating a new data frame
    2. By using "cbind"
    3. By adding column "a", and sort data frame by columns using column names or indexes

    Let me show #4 approach "By using "cbind" and "rename" that works for my case

    1. Create data frame

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

    2. Get values for "new" column

    new_column = c(0, 0, 0)

    3. Combine "new" column with existed

    df <- cbind(new_column, df)

    4. Rename "new" column name

    colnames(df)[1] <- "a"

提交回复
热议问题