0

I have a 1 column table with postcodes in it: I would like to loop through each postcode using the postcode_lookup() function in the postcodeioR library. My current attempts are the following:

x <- data.frame()

for(i in 1:3){
  x[i, ] <- postcode_lookup(table$Var1[i])
}

So i instantiated a new table and tried to add the result of postcode_lookup to a new row every time. But I get nothing. What i get is data frame with 3 obs. and 0 variables. the data should look like this: imagine 31 columns and multiple rows: table

1 Answer 1

1

You need to explicitly specify the number of columns when creating a data frame:

df <- as.data.frame(matrix(NA, 0, 1))

set.seed(123)
val <- runif(20)

for (i in 1:3){
  df[i, ] <- val[[i]]
}

In this case, a matrix with 0 rows and 1 column is converted to a data frame. This is a convenient way to create an empty data frame with the required number of columns.

In your case, you have a data frame with 0 columns. Hence, nothing gets populated.

Sign up to request clarification or add additional context in comments.

3 Comments

That worked very well - thank you!! - One more question if you dont mind - I get the following error when i go beyong 299 times in the for loop: Error in x[[jj]][iseq] <- vjj : replacement has length zero: This is my code: df <- as.data.frame(matrix(NA, 2560, 31)) for (i in 1:length(table$Var1)){ df[i, ] <- postcode_lookup(table$Var1[i]) }
Your right there is an empty vector - problem is that the for loop stops - is it possible for the for loop to keep going and try the next one instead of terminating?
then you need to use two sets of indices in your loop and adjust them accordingly. while loop will be more appropriate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.