R:根据行值中的字符串更改列名称

Sea*_*roc 3 r dplyr

我有一个来自大量 csv 文件的 df 。当前的列名称具有其名称的占位符。有没有办法使每列的名称成为数据的一部分。整个列的字符串将相同。我会手动更改名称,但有 256 列。

开始 df:

   col2          col3       col4     ...
1 version=1    numCh=10   reserved=0
2 version=1    numCh=10   reserved=0
3 version=1    numCh=11   reserved=0
4 version=1    numCh=11   reserved=0
...
Run Code Online (Sandbox Code Playgroud)

所需的输出:

  version    numCh    reserved   ...
1    1        10        0
2    1        10        0
3    1        11        0
4    1        11        0
...
Run Code Online (Sandbox Code Playgroud)

一直在尝试不同的方法,看看其他人是否创造了类似的东西。

akr*_*run 5

提取第一行,并从=with中删除子字符串trimws,然后循环across列,提取数字部分 withparse_number并用第一行的子字符串设置列名

library(dplyr)
 v1 <- trimws(unlist(df1[1,]), whitespace = "=.*")
df1 %>% 
    mutate(across(everything(), readr::parse_number)) %>% 
     setNames(v1)
Run Code Online (Sandbox Code Playgroud)

-输出

  version numCh reserved
1       1    10        0
2       1    10        0
3       1    11        0
4       1    11        0
Run Code Online (Sandbox Code Playgroud)

数据

df1 <- structure(list(col2 = c("version=1", "version=1", "version=1", 
"version=1"), col3 = c("numCh=10", "numCh=10", "numCh=11", "numCh=11"
), col4 = c("reserved=0", "reserved=0", "reserved=0", "reserved=0"
)), class = "data.frame", row.names = c("1", "2", "3", "4"))
Run Code Online (Sandbox Code Playgroud)