ruixin lee
ruixin lee

Reputation: 17

add values to r dataframe

I would like to ask how do i add/append new observations to empty r dataframe. I will be running a loop and I want to update this dataframe as and when the loop is running.

say for instance, I have this dataframe:

error <- data.frame(error_code = character(), row_no = character(), sleep_time = character(), time_scrape = character())

the loop that I will be running is:

for (i in 1:10) {
  if (i %% 2 == 0) {
    error_code = i
    row_no = i
    sleep_time = 60
    time_scrape = i
   }
error <- error %>% 
add_row(error_code = error_code, row_no = row_no, sleep_time = sleep_time, time_scrape = time_scrape)
}

I want to add in the values based on the value I get from the loop

I tried using add_row but it doesnt work. how should I do this such that at the end, I will get something like this: (p/s: this table below is created manually and not by the code above)

error_code row_no sleep_time time_scrape
1          2      2         60          2
2          4      4         60          4

Upvotes: 1

Views: 428

Answers (3)

user13830766
user13830766

Reputation:

I think this should get you what you want:

     e=c();r=c();s=c();t=c()
     
     for (i in 1:10){
     e[i] = 2*i
     r[i] = 2*i
     t[i] = 2*i
     df=data.frame(error_code=e,row_no=r,sleep_time=60,time_scrape=t)
     }
       }
       
       df

Upvotes: 0

StupidWolf
StupidWolf

Reputation: 46978

You can just define the data.frame at one go:

i = as.character(seq(2,10,by=2))
data.frame(error_code = i,row_no = i,sleep_time = 60,time_scrape = i)

If you absolutely, really, must do that, this would be how it works:

error <- data.frame(error_code = character(), row_no = character(), sleep_time = character(), time_scrape = character())

for (i in as.character(seq(2,10,by=2))){

error <- error %>%  
add_row(data.frame(error_code = i,
row_no = i,
sleep_time = as.character(60),
time_scrape = i,stringsAsFactors=FALSE))
}

This is not the best way to go about..And why are all your columns in characters when they look like numeric?

Upvotes: 2

mischva11
mischva11

Reputation: 2956

You could solve this with using rbind, though this is very unperformant. Other solutions like from the other answer might me more convinient. But maybe you need the loop structure. So here you go:

 library(dplyr)

error <- data.frame(error_code = character(), row_no = character(), sleep_time = character(), time_scrape = character())


for (i in 1:10) {
  if (i %% 2 == 0) {
    error_code = i
    row_no = i
    sleep_time = 60
    time_scrape = i
    df<-data.frame(error_code, row_no, sleep_time, time_scrape)
    error <- rbind(error, df)
  }
  #error <- rbind(error, df)
}

Upvotes: 0

Related Questions