简体   繁体   中英

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

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM