-1

I am trying to update a tibble using for loop without any success. Below is my code:-

temp <- tibble(field1="",field2="")
for (i in 1:2){ 
    for (k in 1:2){
        add_row(temp,field1=i,field2=k)
    }}
temp

# A tibble: 1 x 2
  field1 field2
  <chr>  <chr> 
1 ""     ""   

Can you please guide me why this is the case?

divibisan
  • 11,659
  • 11
  • 40
  • 58
itthrill
  • 1,241
  • 2
  • 17
  • 36
  • 1
    you should write `temp <- add_row(temp,field1=i,field2=k)` – MKR Apr 10 '18 at 20:45
  • 4
    `add_row` doesn't change the tibble, it returns a new tibble with the row added. You need to save the new value. `temp <- add_row(temp,field1=i,field2=k)`. But generally this is a very inefficient way to build a tibble. It's better to built all the columns at once. Is there a reason you think you need this strategy? – MrFlick Apr 10 '18 at 20:46
  • 1
    This particular task can be done with `purrr::cross_df(list(field1=1:2, field2=1:2))`. – MrFlick Apr 10 '18 at 20:48

1 Answers1

2

courtesy MKR and MrFlick

temp <- tibble(field1="",field2="")
    for (i in 1:2){ 
        for (k in 1:2){
            temp<-add_row(temp,field1=i,field2=k)
        }}
itthrill
  • 1,241
  • 2
  • 17
  • 36