簡體   English   中英

將rename_if謂詞應用於列名

[英]apply rename_if predicate to column names

我正在使用一組具有日期的列名稱的Excel電子表格。

在使用readxl::read_xlsx()讀取數據后,這些列名稱將成為excel索引日期(即表示從1899-12-30開始經過的天數的整數)

是否可以使用dplyr::rename_if()或類似名稱重命名當前為整數的所有列名? 我編寫了一個函數rename_func ,希望將其應用於所有此類列。

df %>% rename_if(is.numeric, rename_func)不適合,因為is.numeric應用於列中的數據,而不是列名本身。 我也嘗試過:

is.name.numeric <- function(x) is.numeric(names(x))
df %>% rename_if(is.name.numeric, rename_func)

這不起作用並且不更改任何名稱(即is.name.numeric對所有is.name.numeric返回FALSE

編輯:這是我的數據的虛擬版本

df_badnames <- structure(list(Level = c(1, 2, 3, 3, 3), Title = c("AUSTRALIAN TOTAL", 
"MANAGERS", "Chief Executives, Managing Directors & Legislators", 
"Farmers and Farm Managers", "Hospitality, Retail and Service Managers"
), `38718` = c(213777.89, 20997.52, 501.81, 121.26, 4402.7), 
    `38749` = c(216274.12, 21316.05, 498.1, 119.3, 4468.67), 
    `38777` = c(218563.95, 21671.84, 494.08, 118.03, 4541.02), 
    `38808` = c(220065.05, 22011.76, 488.56, 116.24, 4609.28)), row.names = c(NA, 
-5L), class = c("tbl_df", "tbl", "data.frame"))

我想:

df_goodnames <- structure(list(Level = c(1, 2, 3, 3, 3), Title = c("AUSTRALIAN TOTAL", 
"MANAGERS", "Chief Executives, Managing Directors & Legislators", 
"Farmers and Farm Managers", "Hospitality, Retail and Service Managers"
), Jan2006 = c(213777.89, 20997.52, 501.81, 121.26, 4402.7), 
    Feb2006 = c(216274.12, 21316.05, 498.1, 119.3, 4468.67), 
    Mar2006 = c(218563.95, 21671.84, 494.08, 118.03, 4541.02), 
    Apr2006 = c(220065.05, 22011.76, 488.56, 116.24, 4609.28)), row.names = c(NA, 
-5L), class = c("tbl_df", "tbl", "data.frame"))

我知道創建date列並更改此df的形狀是最佳實踐,但是我需要先加入一些電子表格,並且使用整數列名會帶來很多問題。 我目前有一個解決方法,但是問題的症結(將rename_if謂詞應用於名稱,而不是列)仍然很有趣。

雖然名稱看起來是數字,但不是

class(names(df_badnames))
#[1] "character"

因此它們不會被is.numeric或類似的其他函數捕獲。

一種方法是找出可以強制轉換為數字的names ,然后將其轉換為我們選擇的日期格式

cols <- as.numeric(names(df_badnames))
names(df_badnames)[!is.na(cols)] <- format(as.Date(cols[!is.na(cols)], 
                                          origin = "1899-12-30"), "%b%Y")

df_badnames

#  Level Title                                           Jan2006 Feb2006 Mar2006 Apr2006
#   <dbl> <chr>                                             <dbl>   <dbl>   <dbl>   <dbl>
#1     1 AUSTRALIAN TOTAL                                213778. 216274. 218564. 220065.
#2     2 MANAGERS                                         20998.  21316.  21672.  22012.
#3     3 Chief Executives, Managing Directors & Legisla…    502.    498.    494.    489.
#4     3 Farmers and Farm Managers                          121.    119.    118.    116.
#5     3 Hospitality, Retail and Service Managers          4403.   4469.   4541.   4609.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM