Add a new column or variable to a table in R

Add a new column or variable to a table in R


# In R, rows are called observations and columns are called variables

We have a table below called tabletrains with four variables and we want to add another variable/column called "distance"

tabletrains
TrainNo From To DateofJourney
12863 HWH YPR 21-Nov-15
12245 HWH YPR 21-Nov-15
12378 NJP SDAH 20-Nov-15
52544 DJ KGN 18-Nov-15
13149 BWN NJP 15-Nov-15
12864 KJM HWH 13-Nov-15
12864 KJM HWH 10-Nov-15
12640 KJM MAS 4-Nov-15
12840 MAS HWH 4-Nov-15
12246 YPR HWH 16-Aug-15

Steps:

install.packages("dplyr") # hit Ctrl + Enter
library(dplyr)                   # hit Ctrl + Enter

# once the package in loaded,

tabletrains <- tabletrains %>%
                      mutate("distance") # Select the code and hit Ctrl + Enter

# Check results
head(tabletrains)
names(tabletrains)

# If you want to assign a value to distance e.g., distance = 1000 km then


tabletrains <- tabletrains %>%

                      mutate(distance = 1000) # Select the code and hit Ctrl + Enter


# Check results

head(tabletrains)



Comments