如何在 R 中重命名带有月份年份的数据框列

问题描述 投票:0回答:1

我正在阅读 xlsx,其中有一些日期列名称为

Name <- c("some data")
Date <- c("some data")
ID <- c("some data")
`comprehensive (Monthly) 2022-01` <- c( "some data")
`comprehensive (Monthly) 2022-02`  <- c( "some data")
`comprehensive (Monthly) 2022-03` <- c( "some data")
`comprehensive (Monthly) 2022-04`  <- c( "some data")
`comprehensive (Monthly) 2022-05` <- c( "some data")
`comprehensive (Monthly) 2022-06`  <- c( "some data")
`comprehensive (Monthly) 2022-07` <- c( "some data")
`comprehensive (Monthly) 2022-08`  <- c( "some data")


df <- data.frame(
Name,
Date,
ID,
`comprehensive (Monthly) 2022-01`,
`comprehensive (Monthly) 2022-02`,
`comprehensive (Monthly) 2022-03`,
`comprehensive (Monthly) 2022-04`)

我只想重命名All列,例如comprehensive (Monthly) 2022-01

并写入新的xlsx文件。
实现下面最终结果的最佳方法是什么?

我可以写一个像下面这样的函数吗

strsplit

function(df) { temp <- (df) temp$`comprehensive (Monthly) 2022-01`<- strsplit(df)[[1]][2] return(temp) |> write.xlsx(new_df) }
new_df

Name <- c("some data")
Date <- c("some data")
ID <- c("some data")
`2022-01` <- c( "some data")
`2022-02`  <- c( "some data")
`2022-03` <- c( "some data")
`2022-04`  <- c( "some data")
`2022-05` <- c( "some data")
`2022-06`  <- c( "some data")
`2022-07` <- c( "some data")
`2022-08`  <- c( "some data")
    
r excel xlsx lubridate
1个回答
0
投票
这里有几个在 hte 数据框的现有名称上使用

names<-

 和正则表达式子函数的示例:

names(df) <- sub("comprehensive|\\(|\\)", "", names(df)) df #----------------------- Name Date ID ..Monthly..2022.01 ..Monthly..2022.02 ..Monthly..2022.03 ..Monthly..2022.04 1 some data some data some data some data some data some data some data names(df) <- sub("comprehensive|\\(|\\)|\\c", "", names(df)) #---------- df #----------- Name Date ID ..Monthly..2022.01 ..Monthly..2022.02 ..Monthly..2022.03 ..Monthly..2022.04 1 some data some data some data some data some data some data some data #-------------- names(df) <- gsub("comprehensive|\\(|\\)|\\.", "", names(df)) # remove periods df #------------- Name Date ID Monthly202201 Monthly202202 Monthly202203 Monthly202204 1 some data some data some data some data some data some data some data
R 正则表达式模式中的所有特殊字符都需要进行双重转义。

© www.soinside.com 2019 - 2024. All rights reserved.