How to add a new column to a dataframe in R?
Let us create a dataframe with some values in R.For doing this we have to select a dataframe for selecting rows and columns. A data frame is a structure having 2 dimensions which contains data in the form of rows and columns. It can be spreadsheet data and can be represented in the form of tables or dictionaries of series.
Let us build two vectors where one will be consisting of integers and the other will be consisting strings.
c1 <- 1:10 # vector of integers
c2 <- letters[1:10] # vector of strings
Now let us build a dataframe combining the two vectors c1 and c2.
df <- data.frame(col.name.1=c1,col.name.2=c2)
df
Now to add a new column, we can do the following
df$newcol <- rep(NA, nrow(df)) # NA column
df
A new column is added having null values