簡體   English   中英

如何重命名在 r 中使用 str_detect 找到的列?

[英]How to rename a column that is found using str_detect in r?

我想從數據框中替換一個列名,以便我可以更新該列中的值。 但是,如果有人可以告訴我如何做到這一點,我願意接受替代和更好的方法來做到這一點。

查找以 Org 開頭並以 Type 結尾的列名。 有時不同來源的數據框可能有不同的列名。 另外,最好讓它不區分大小寫**

org_type_col <- names(assessment) %>% str_subset("(Org)(.*)(Type)") 
assessment <- assessment %>% setNames(org_type_col = "OrgType")

但這是我遇到錯誤的地方。 我得到的錯誤是這樣的:

Error in setNames(., org_type_col = "OrgType") : unused argument (org_type_col = "OrgType")

我想重命名列,以便我可以執行以下操作:

### Organization Type

assessment <- assessment %>% 
  add_column(OrganizationType = case_when(
(str_detect(.$OrgType, "Health")) ~ "Healthcare", 
(str_detect(.$OrgType, "Pharmaceuticals")) ~ "Pharmaceuticals",
(str_detect(.$OrgType, "Banking|Financial|Insurance")) ~ "Financial Services",
(str_detect(.$OrgType, "Computer|Telecommunication")) ~ "High-Tech",
(str_detect(.$OrgType, "Energy|Utilities")) ~ "Energy",
(str_detect(.$OrgType, "Education")) ~ "Education",
(str_detect(.$OrgType, "Government")) ~ "Government")) %>%
replace_na(list(OrgType = "Unknown"))

有沒有更簡單更好的方法來將它們全部結合起來?

在基礎 R 中,您可以執行以下操作:

names(assessment)[grepl('^Org.*Type$', names(assessment), ignore.case = TRUE)] <- 'OrgType'

如果您對tidyverse解決方案感興趣,可以嘗試:

library(dplyr)
library(stringr)

assessment %>%
  rename_with(~str_detect(.,regex('^Org.*Type$', ignore_case = TRUE)), 'OrgType')

暫無
暫無

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

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