Advertisements
# Creating an empty dataframe
result_df <- data.frame()
# Iterating over the numbers 1 to 3
for (i in 1:3) {
# Create a new column and populate it with values of i
result_df[, paste0("Column", i)] <- i
}
I expect to have the following populated dataframe:
Column1 Column2 Column3
1 1 2 3
>Solution :
R is vectorized and this can be done without loops at all.
Note that nums <- seq_len(3)
is an alternative way of creating the vector nums
.
nums <- 1:3
row <- setNames(nums, paste0("Column", nums))
as.data.frame(t(row))
#> Column1 Column2 Column3
#> 1 1 2 3
Created on 2023-06-03 with reprex v2.0.2