将列名称分配给数据集的 select 列

Assign column names to select columns of dataset

我导入了 in which the columns from #5 onwards are dates that need to be cleaned as they have the form X1.10.20 and I would like to have the format YYYY-MM-DD. I am using gsub() to clean the data into a recognizable form for 然后用 mdy()

转换
library(tidyverse)
library(lubridate)

df <- read.csv("df.csv", stringsAsFactors = FALSE)
names(df) <- gsub("X", "", names(df))           #remove leading X
names(df) <- gsub("\.", "-", names(df))        #convert . to -

带日期的列现在采用以下格式:M-D-YY

dates <- mdy(names(df[,-c(1:4)])) #take current names and assign converted names to `dates` vector

日期向量现在包含 YYYY-MM-DD 格式的日期。我想使用这个 dates 向量并将其分配为列 4:length(df)

中的名称

我试过以下方法:

names(df[,-c(1:4)]) <- dates ,但是原始数据框中的列名保持不变。并保持格式 M-D-YY

我觉得我可能想多了,可能有更简单的方法来重命名特定的列。我也从 尝试过 rename(),但只在单独命名列方面取得了成功,而且这个数据集有数百列。

我该怎么做?感谢您的输入...

names 参数应该是

library(lubridate)
dates <- as.character(mdy(names(df)[-c(1:4)]))
names(df)[-c(1:4)] <- dates

如果我们使用 check.names = FALSE

就可以避免这种情况
df <- read.csv("df.csv", stringsAsFactors = FALSE, check.names = FALSE)