Home > Blockchain >  How do I save a single column of data produced from a while loop in R to a dataframe?
How do I save a single column of data produced from a while loop in R to a dataframe?

Time:11-05

I have written the following very simple while loop in R.

i=1
while (i <= 5) {
  print(10*i)
  i = i 1
}

I would like to save the results to a dataframe that will be a single column of data. How can this be done?

CodePudding user response:

You may try(if you want while)

df1 <- c()
i=1
while (i <= 5) {
  print(10*i)
  df1 <- c(df1, 10*i)
  i = i 1
}
as.data.frame(df1)

  df1
1  10
2  20
3  30
4  40
5  50

Or

df1 <- data.frame()
i=1
while (i <= 5) {
  df1[i,1] <- 10 * i
  i = i 1
}
df1

CodePudding user response:

If you already have a data frame (let's call it dat), you can create a new, empty column in the data frame, and then assign each value to that column by its row number:

# Make a data frame with column `x`
n <- 5
dat <- data.frame(x = 1:n)

# Fill the column `y` with the "missing value" `NA`
dat$y <- NA

# Run your loop, assigning values back to `y`
i <- 1
while (i <= 5) {
  result <- 10*i
  print(result)
  dat$y[i] <- result
  i <- i 1
}

Of course, in R we rarely need to write loops like his. Normally, we use vectorized operations to carry out tasks like this faster and more succinctly:

n <- 5
dat <- data.frame(x = 1:n)

# Same result as your loop
dat$y <- 10 * (1:n)

Also note that, if you really did need a loop instead of a vectorized operation, that particular while loop could also be expressed as a for loop.

I recommend consulting an introductory book or other guide to data manipulation in R. Data frames are very powerful and their use is a necessary and essential part of programming in R.

  • Related