如何通过对重复项进行编号而不是按其列位置来替换 readr 包的 name_repair 行为?

pie*_*ito 0 r rename readr

假设我有这个 csv 文件:

\n
asdf,qwer,asdf,qwer,qwer\n1,2,3,4,5\n
Run Code Online (Sandbox Code Playgroud)\n

如果我用来readr::read_csv("some.csv")阅读它,我将根据列的位置获得重复项的新列名称。

\n
# A tibble: 1 \xc3\x97 5\n  asdf...1 qwer...2 asdf...3 qwer...4 qwer...5\n     <dbl>    <dbl>    <dbl>    <dbl>    <dbl>\n1        1        2        3        4        5\n
Run Code Online (Sandbox Code Playgroud)\n

如果我宁愿使用基于重复次数的后缀的名称,并且对于第一次出现时不做任何修改,我该怎么办:

\n
# A tibble: 1 \xc3\x97 5\n   asdf  qwer asdf_1 qwer_1 qwer_2\n  <dbl> <dbl>  <dbl>  <dbl>  <dbl>\n1     1     2      3      4      5\n
Run Code Online (Sandbox Code Playgroud)\n
\n

暗示

\n

似乎可以使用 的name_repair参数read_csv并提供一个函数。

\n

r2e*_*ans 6

由于name_repair=can是一个函数,我们可以通过编程的方式处理它。幸运的是,base::make.unique它可以完成大部分工作,并且我们可以对其进行自定义sep="_"以获得准确的输出。

\n
namefun <- function(nm) make.unique(nm, sep = "_")\ntxt <- \'asdf,qwer,asdf,qwer,qwer\n1,2,3,4,5\'\nreadr::read_csv(txt, name_repair = namefun)\n# Rows: 1 Columns: 5\n# \xe2\x94\x80\xe2\x94\x80 Column specification \xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\n# Delimiter: ","\n# dbl (5): asdf, qwer, asdf_1, qwer_1, qwer_2\n# \xe2\x84\xb9 Use `spec()` to retrieve the full column specification for this data.\n# \xe2\x84\xb9 Specify the column types or set `show_col_types = FALSE` to quiet this message.\n# # A tibble: 1 \xc3\x97 5\n#    asdf  qwer asdf_1 qwer_1 qwer_2\n#   <dbl> <dbl>  <dbl>  <dbl>  <dbl>\n# 1     1     2      3      4      5\n
Run Code Online (Sandbox Code Playgroud)\n