To add new column to data frame in R, you can use two different methods.
The following methods show how you can do it with syntax.
Method 1: Use $ Operator
df$new_column <- c(value1,value2,value3,....)
Method 2: Use cbind() Function
df <- cbind(df,new_column = c(value1,value2,value3,....))
Let’s first create data frame using data.frame() function:
# Create data frame
df <- data.frame(Start_date=as.Date(c("2000-05-21","1998-03-28","2001-01-19","2003-04-27","2004-11-26","2008-11-25")),
Machine_name = c("Machine1","Machine2","Machine3","Machine4","Machine5","Machine6"),
Value = c(108,120,135,95,98,105),Reading= c(110,97,91,89,80,85))
# Print data frame
print(df)
Output:
Start_date Machine_name Value Reading
1 2000-05-21 Machine1 108 110
2 1998-03-28 Machine2 120 97
3 2001-01-19 Machine3 135 91
4 2003-04-27 Machine4 95 89
5 2004-11-26 Machine5 98 80
6 2008-11-25 Machine6 105 85
The output shows data frame that we created in above code.
The following examples show how to add new column to data frame in R.
Use $ Operator to Add Column to Dataframe
Let’s see how we can add new column to data frame:
# Create data frame
df <- data.frame(Start_date=as.Date(c("2000-05-21","1998-03-28","2001-01-19","2003-04-27","2004-11-26","2008-11-25")),
Machine_name = c("Machine1","Machine2","Machine3","Machine4","Machine5","Machine6"),
Value = c(108,120,135,95,98,105),Reading= c(110,97,91,89,80,85))
# Add new column to data frame
df$Working <- c(TRUE,TRUE,FALSE,FALSE,TRUE,FALSE)
# Print data frame
print(df)
Output:
Start_date Machine_name Value Reading Working
1 2000-05-21 Machine1 108 110 TRUE
2 1998-03-28 Machine2 120 97 TRUE
3 2001-01-19 Machine3 135 91 FALSE
4 2003-04-27 Machine4 95 89 FALSE
5 2004-11-26 Machine5 98 80 TRUE
6 2008-11-25 Machine6 105 85 FALSE
As the output shows data frame which having new column added to it.
Use cbind() Function to Add New Column to Dataframe
You can use cbind() function to add new column to data frame in R:
# Create data frame
df <- data.frame(Start_date=as.Date(c("2000-05-21","1998-03-28","2001-01-19","2003-04-27","2004-11-26","2008-11-25")),
Machine_name = c("Machine1","Machine2","Machine3","Machine4","Machine5","Machine6"),
Value = c(108,120,135,95,98,105),Reading= c(110,97,91,89,80,85))
# Add new column to data frame
df <- cbind(df,Working = c(TRUE,TRUE,FALSE,FALSE,TRUE,FALSE))
# Print data frame
print(df)
Output:
Start_date Machine_name Value Reading Working
1 2000-05-21 Machine1 108 110 TRUE
2 1998-03-28 Machine2 120 97 TRUE
3 2001-01-19 Machine3 135 91 FALSE
4 2003-04-27 Machine4 95 89 FALSE
5 2004-11-26 Machine5 98 80 TRUE
6 2008-11-25 Machine6 105 85 FALSE
As the output shows data frame with newly added column to it.