gpt4 book ai didi

动态重新编码列

转载 作者:行者123 更新时间:2023-12-01 22:53:05 25 4
gpt4 key购买 nike

如何使用函数重新编码列,该函数根据传递的参数决定将旧变量名称更改为哪个名称?

library(sjstats) # has example data
library(tidyverse)

data(efc)

# Function to decide the name of the variable
decide_name <- function(c161sex) {
name <- case_when(
c161sex == 1 ~ "Male",
c161sex == 2 ~ "Female",
TRUE ~ "missing"
)
return(name)
}

根据返回的值动态重新编码变量(每个数据集将有 1 个且只有 1 个变量“c161sex”值)

efc_renamed <- efc %>%
rename(decide_name = e42dep)

最佳答案

您需要的是recode(),而不是rename()

recode_dynam <- function(var) {
recode(var, `1` = "Male", `2` = "Female", .default = "missing", .missing = "missing")
}
测试
efc_recoded <- efc %>%
mutate(e42dep = recode_dynam(e42dep))

efc_recoded %>%
count(e42dep)

# e42dep n
# 1 Female 225
# 2 Male 66
# 3 missing 617

关于动态重新编码列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73828979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com