r - 如何将整行作为列名?

对于以下数据框,我想将列名称更改为第一列以一个或多个单词开头的行。这是第 2 行和单词 Company。但是,行可以不同,例如具有不同数据框的第 1、5 或第 10 行,单词也可以不同,例如 Investment 和其他。

structure(list(X1 = c("", "Company #", "Investments:"
), X2 = c("", "Type", ""), X3 = c("", "Reference", 
""), X4 = c(NA_real_, NA_real_, NA_real_), X5= c("", "Footnotes", 
""), X6 = c(NA_character_, NA_character_, NA_character_)), row.names = c(NA, 
3L), class = "data.frame")

          X1             X2       X3        X4       X5       X6
    <chr>              <chr>    <chr>      <dbl>   <chr>    <chr>
1                                           NA               NA
2   Company #           Type   Reference    NA   Footnotes   NA
3   Investments:                            NA               NA

我想首先获取第 1 列以一个/多个单词开头的行号,然后使用该行号更改为列名,或者可能有更好的方法来做到这一点。

names(my_df)<- my_df[row_number,]
my_df <- my_df[-row_number,]

期望的输出

        Company #   Type   Reference    NA   Footnotes    NA
    <chr>           <chr>   <chr>      <dbl>   <chr>    <chr>
3   Investments:                         NA              NA

最佳答案

#row number of the first word in the first column
row_n <- min(which(nzchar(my_df[[1]])))
janitor::row_to_names(my_df, row_n)

输出

#     Company # Type Reference NA Footnotes   NA
#3 Investments:                NA           <NA>

请注意,如果这样做,您将拥有非唯一的列名 (NA)。您可以使用 clean_names 快速解决这个问题。

https://stackoverflow.com/questions/75021979/

相关文章:

c# - C# 是否有某种 value_or_execute 或 value_or_throw?

c - 尝试复制有关可变参数的 printf 行为

python - 无法使用调试暂停 python 进程

haskell - 减少围绕手工包装的 `Num` 类型的样板

powershell - 如何在 PowerShell 方法链接中使用换行符

LUA - 表中最常见的项目

python - Pandas 将 df.count() 结果的最后 n 行求和为一行

r - 在 mutate 中将参数传递给 pmap

arrays - 如何将数组的元素移动到数组的开头

python - 什么时候值得在 if-else 语句上使用循环?