【问题标题】:How to Insert rows into a single column in an empty dataframe in R?如何将行插入R中空数据框中的单列?
【发布时间】:2021-01-26 18:03:57
【问题描述】:

我有以下空数据框/tibble:

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

)

创建 0 行 x 2 列后为空

我有以下代码数据框:

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

看起来像这样:

codes 
-----
CH
US
UK

有没有办法循环遍历 df_codes 数据帧中的每个元素并将这些值插入到我的 new_table 数据帧代码列中?

我尝试了以下代码,但无济于事:

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

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

return(new_table)
}

但这仍然返回一个 0 行 2 列的数据框:

理想情况下,我希望在调用 new_table 时得到这个输出:

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

感谢任何帮助

【问题讨论】:

  • 您在第一次通过循环后立即返回(从哪里来?)。

标签: r dataframe dplyr tidyverse


【解决方案1】:

我们可以使用bind_rows

library(dplyr)
bind_rows(new_table, df_codes)

-输出

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

或者不使用bind_rows,这可以通过分配base R 来完成

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

在哪里

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

【讨论】:

    【解决方案2】:

    另一个基本 R 选项是 merge

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

    给了

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多