gpt4 book ai didi

r - 如何使用 R 将包含 if-else 结构的函数用于每一列

转载 作者:行者123 更新时间:2023-12-02 05:33:14 25 4
gpt4 key购买 nike

数据框sg如下:

 v1 v2 v3 
A B C
B A B
C A A

我用了一个函数

definition <- funciton(x){
if (x =='A') definition <- paste(x, ": MINIMUM_RED")
else if (x =='B') definition <- paste(x, ": PASSIVE_RED") ## Passive red (no green demand during red)
else if (x =='C') definition <- paste(x, ": RED_REQUEST") ## During red the group has a green demand
else if (x =='D') definition <- paste(x, ": RED_PRIORITY")
else if (x =='E') definition <- paste(x, ": RED_PRIVILEGE") ## During red possilbe to go green
else definition <- paste(x, ": RED_WAIT") ##
}

我想对数据框 sg 中的每个值使用函数定义,所以我使用了应用函数:

sgdf <- apply(sg,2,defination)

结果如下:

     [,1]              [,2]              [,3]             
[1,] "A : MINIMUM_RED" "B : PASSIVE_RED" "C : RED_REQUEST"
[2,] "B : MINIMUM_RED" "A : PASSIVE_RED" "B : RED_REQUEST"
[3,] "C : MINIMUM_RED" "A : PASSIVE_RED" "A : RED_REQUEST"

显然,该函数仅适用于每列中的第一个元素,我有什么方法可以获得每个值的正确定义吗?

最佳答案

您可以只使用一个列表将每个字符映射到一个定义。

例如

sg <- data.frame(v1=c("A", "B", "C"),
v2=c("B", "A", "A"),
v3=c("C", "A", "A"))

defs <- list("A" = "MINIMUM_RED",
"B" = "PASSIVE_RED",
"C" = "RED_REQUEST",
"D" = "RED_PRIORITY",
"E" = "RED_PRIVILEGE")

# Convert the data frame in a matrix, so we can use it to index the list
tmp <- as.matrix(sg)

# note that paste works on vectors
res <- matrix(paste(tmp, defs[tmp]), ncol=ncol(tmp))

导致:

     [,1]            [,2]            [,3]           
[1,] "A MINIMUM_RED" "B PASSIVE_RED" "C RED_REQUEST"
[2,] "B PASSIVE_RED" "A MINIMUM_RED" "A MINIMUM_RED"
[3,] "C RED_REQUEST" "A MINIMUM_RED" "A MINIMUM_RED"

关于r - 如何使用 R 将包含 if-else 结构的函数用于每一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25119462/

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