Beans On Toast
Beans On Toast

Reputation: 1081

How to Insert rows into a single column in an empty dataframe in R?

I have the following empty dataframe/tibble:

new_table <- tibble(
  country = character(),
  code = character()

)

Which is empty after creating it 0 rows x 2 columns

And i have the following data frame of codes:

df_codes <- tibble(codes = c('CH','US','UK'))

which looks like this:

codes 
-----
CH
US
UK

Is there way of looping through each element in the df_codes dataframe and inserting these values into my new_table dataframes code column?

I have tried the following code but to no avail:

for(c in unique(df_codes$codes)){

new_table <- new_table %>% mutate(code = c)

return(new_table)
}

But this returns still a dataframe with 0 rows and 2 columns:

Ideally i would like this output when calling new_table:

country|code
-------|-----
NA     | CH
NA     | US
NA     | UK

Any help is appreciated

Upvotes: 1

Views: 509

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 101753

Another base R option is merge

merge(new_table,df_codes, by.x = "code", by.y = "codes",all = TRUE)

which gives

  code country
1   CH    <NA>
2   UK    <NA>
3   US    <NA>

Upvotes: 0

akrun
akrun

Reputation: 887223

We can just use bind_rows

library(dplyr)
bind_rows(new_table, df_codes)

-output

# A tibble: 3 x 2
#  country code 
#  <chr>   <chr>
#1 <NA>    CH   
#2 <NA>    US   
#3 <NA>    UK   

Or instead of using bind_rows, this can be done with base R by doing an assignment

new_table[seq_len(nrow(df_codes)), names(df_codes)] <- df_codes

where

df_codes <- tibble(code = c('CH','US','UK'))

Upvotes: 2

Related Questions