Cómo agregar una nueva variable a un dataframe existente, pero quiero agregar al frente y al final. p.ej. mi dataframe es
bcd 1 2 3 1 2 3 1 2 3
Quiero agregar una nueva variable a, para que el dataframe se vea como
abcd 0 1 2 3 0 1 2 3 0 1 2 3
Use cbind
por ejemplo
df <- data.frame(b = runif(6), c = rnorm(6)) cbind(a = 0, df)
dando:
> cbind(a = 0, df) abc 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
df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3)) df ## bcd ## 1 1 2 3 ## 2 1 2 3 ## 3 1 2 3 df <- data.frame(a = c(0, 0, 0), df) df ## abcd ## 1 0 1 2 3 ## 2 0 1 2 3 ## 3 0 1 2 3
Agregar la columna “a”
> df["a"] <- 0 > df bcda 1 1 2 3 0 2 1 2 3 0 3 1 2 3 0
Ordenar por columna usando nombre de columna
> df <- df[c('a', 'b', 'c', 'd')] > df abcd 1 0 1 2 3 2 0 1 2 3 3 0 1 2 3
O ordenar por columna usando el índice
> df <- df[colnames(df)[c(4,1:3)]] > df abcd 1 0 1 2 3 2 0 1 2 3 3 0 1 2 3
Si desea hacerlo de manera tidyverse
, intente add_column
from tibble
, que le permite especificar dónde colocar la nueva columna con el parámetro .before
o .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) # abcd # 1 0 1 2 3 # 2 0 1 2 3 # 3 0 1 2 3
Las respuestas anteriores muestran 3 enfoques
Déjame mostrar el enfoque # 4 “Al usar” cbind “y” rename “que funciona para mi caso
df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
new_column = c(0, 0, 0)
df <- cbind(new_column, df)
colnames(df)[1] <- "a"
cbind inherents orden por su orden de argumento.
El usuario su primera columna (s) como su primer argumento
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