Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I put the iterable numbers into a new column each iteration?

# 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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading