Add New Column to Data Frame in for-Loop in R (Example Code)
This article illustrates how to append a new variable or row to a data frame in R using a for-loop.
Introduction of Example Data
data(iris) # Loading iris data set head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa |
data(iris) # Loading iris data set head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width Species # 1 5.1 3.5 1.4 0.2 setosa # 2 4.9 3.0 1.4 0.2 setosa # 3 4.7 3.2 1.3 0.2 setosa # 4 4.6 3.1 1.5 0.2 setosa # 5 5.0 3.6 1.4 0.2 setosa # 6 5.4 3.9 1.7 0.4 setosa
Example: Append New Column to Data Frame Using for-Loop in R
for(index in 1:3) { # Running for-loop add_col <- paste0("index", index, "_row", 1:nrow(iris)) # Creating new variable iris[ , ncol(iris) + 1] <- add_col # Appending new variable to data } |
for(index in 1:3) { # Running for-loop add_col <- paste0("index", index, "_row", 1:nrow(iris)) # Creating new variable iris[ , ncol(iris) + 1] <- add_col # Appending new variable to data }
head(iris) # Showing new data # Sepal.Length Sepal.Width Petal.Length Petal.Width Species V6 V7 V8 # 1 5.1 3.5 1.4 0.2 setosa index1_row1 index2_row1 index3_row1 # 2 4.9 3.0 1.4 0.2 setosa index1_row2 index2_row2 index3_row2 # 3 4.7 3.2 1.3 0.2 setosa index1_row3 index2_row3 index3_row3 # 4 4.6 3.1 1.5 0.2 setosa index1_row4 index2_row4 index3_row4 # 5 5.0 3.6 1.4 0.2 setosa index1_row5 index2_row5 index3_row5 # 6 5.4 3.9 1.7 0.4 setosa index1_row6 index2_row6 index3_row6 |
head(iris) # Showing new data # Sepal.Length Sepal.Width Petal.Length Petal.Width Species V6 V7 V8 # 1 5.1 3.5 1.4 0.2 setosa index1_row1 index2_row1 index3_row1 # 2 4.9 3.0 1.4 0.2 setosa index1_row2 index2_row2 index3_row2 # 3 4.7 3.2 1.3 0.2 setosa index1_row3 index2_row3 index3_row3 # 4 4.6 3.1 1.5 0.2 setosa index1_row4 index2_row4 index3_row4 # 5 5.0 3.6 1.4 0.2 setosa index1_row5 index2_row5 index3_row5 # 6 5.4 3.9 1.7 0.4 setosa index1_row6 index2_row6 index3_row6