R如果返回数据框列中的列表需要简单字符
问题上下文:返回的列表需要chr字符。创建函数fun_grade,有条件地选择数值作为字符,以便在数据帧内返回和更新。在数据框df_credit_status$grade字段中返回了一个列表。也许我需要转换为as.character,或者是否有更好的函数方法来更改character列R如果返回数据框列中的列表需要简单字符,r,function,if-statement,switch-statement,R,Function,If Statement,Switch Statement,问题上下文:返回的列表需要chr字符。创建函数fun_grade,有条件地选择数值作为字符,以便在数据帧内返回和更新。在数据框df_credit_status$grade字段中返回了一个列表。也许我需要转换为as.character,或者是否有更好的函数方法来更改character列 list returned need simple chr fun_grade <- function(grade) { if (grade == "A") return("100") if (gr
list returned need simple chr
fun_grade <- function(grade) {
if (grade == "A") return("100")
if (grade == "B") return("80")
if (grade == "C") return("60")
if (grade == "D") return("40")
if (grade == "D") return("20")
if (grade == "F") return("10")
return
}
df_credit_status$grade <- sapply(df_credit_status$grade, FUN=fun_grade)
使用命名向量替换值,而不是执行多个if条件
setNames(c(100, 80, 60, 40, 20, 10),
LETTERS[1:6])[as.character(df_credit_status$grade)]
使用一个小的可重复的例子
set.seed(24)
v1 <- sample(LETTERS[1:6], 25, replace = TRUE)
setNames(c(100, 80, 60, 40, 20, 10), LETTERS[1:6])[v1]
# C B C E B F B A D A A E E A E E D E B A D C E B A
# 60 80 60 20 80 10 80 100 40 100 100 20 20 100 20 20 40 20 80 100 40 60 20 80 100
另外,如果/else没有矢量化,那么需要时可以使用ifelse/if_else/case_,但无论如何效率都不高好的,我模拟了一个数据帧:
df_credit_status hey非常感谢,以前从未使用过setName,非常简洁的小代码解决方案hey非常感谢。。。我的wifi很晚才恢复,在你宝贵的帮助下一切正常
> head(df_credit_status)
grade equiv_grade
1 F 10
2 D 40
3 F 10
4 F 10
5 C 60
6 C 60
library(tidyverse)
df_credit_status <- data.frame(
grade = sample(
c("A", "B", "C", "D", "E", "F"),
size = 200,
replace = TRUE)
)
df_credit_status <- df_credit_status %>%
mutate(
equiv_grade = case_when(
grade == "A" ~ "100",
grade == "B" ~ "80",
grade == "C" ~ "60",
grade == "D" ~ "40",
grade == "E" ~ "20",
grade == "F" ~ "10"
)
)
# change the equivalencies above to numbers if you need that