根据不同的数据框架更改列名

  • 本文关键字:框架 数据 r
  • 更新时间 :
  • 英文 :


我有一个名为data_dict的数据字典,它的格式有数百行:

字段名 字段标签
marital_status 您的婚姻状况如何?
出生地 你出生在哪个国家?

我们可以使用rename

library(dplyr)
library(tibble)
df %>% 
summarise(across(all_of(data_dict$"Field Name"),
~ list(table(.x, useNA = "ifany")))) %>%
rename(!!! deframe(data_dict[2:1]))

或使用map

library(purrr)
df %>%
rename(!!! deframe(data_dict[2:1])) %>%
map(~ table(.x, useNA = "ifany")) 

与产出

$record_id
.x
1 2 
1 1 
$`What is your marital status?`
.x
3 6 
1 1 
$`What country were you born?`
.x
12 66 
1  1 

数据
df <- structure(list(record_id = 1:2, marital_status = c(3L, 6L), birthplace = c(66L, 
12L)), class = "data.frame", row.names = c(NA, -2L))
data_dict <- structure(list(`Field Name` = c("marital_status", "birthplace"
), `Field Label` = c("What is your marital status?", "What country were you born?"
)), class = "data.frame", row.names = c(NA, -2L))

最新更新