Install and load package “tibble”.
df <- tibble(x = 1:3, y = 3:1)
In this way, the column is added in the end of the data frame.
df$c <- seq(5,7,by=1)
df
## # A tibble: 3 x 3
## x y c
## <int> <int> <dbl>
## 1 1 3 5
## 2 2 2 6
## 3 3 1 7
We need to create a vector first that we can add as new variable to our data frame.
df <- tibble(x = 1:3, y = 3:1)
c <- seq(5,7,by=1)
c
## [1] 5 6 7
Then apply add_column function by index.
new.df1 <- add_column(df, c, .after = 1) # Apply add_column function by index
new.df1
## # A tibble: 3 x 3
## x c y
## <int> <dbl> <int>
## 1 1 5 3
## 2 2 6 2
## 3 3 7 1
Or, apply add_column function by column name.
df <- tibble(x = 1:3, y = 3:1)
c <- seq(10,12,by=1)
c
## [1] 10 11 12
new.df2 <- add_column(df, c, .after = "x") # Apply add_column function by name
new.df2
## # A tibble: 3 x 3
## x c y
## <int> <dbl> <int>
## 1 1 10 3
## 2 2 11 2
## 3 3 12 1