如何编写具有条件查找功能的顺序 for 循环

How to write a sequential for loop with conditional lookup capability

这里是初学者。 我正在尝试编写一个 for 循环来调整分数。 for 循环的第一部分创建一个条件输出,该输出应传递给具有查找功能的 for 循环的第二部分。

第一个data.frame,a,有2列

第二个data.frame,b,有5列

在第一个 for 循环中,我找到索引所在的位置 a$score = b$score

然后在第二个循环中,我将索引传递给另一个循环。 根据 a$problem 中的值,循环 returns (q, r, s, t) 中的正确调整值。

这里是data.frame一个

id      score   problem
1       11      1
2       12      6
3       13      2
4       14      0
5       NA      NA

这里是data.frameb

score   q   r   s   t
11      12  13  11  NA
12      14  15  12  NA
13      16  20  13  NA
14      18  22  14  NA
NA      NA  NA  NA  NA

我希望函数的输出是 a, a$adjusted

中的一个新列

这是我一直在尝试的功能,

adjust <- function (y, z){

# y = problem
# z = score

  for(j in z){
    index <- sapply(j, function(x) b$score %in% x)
    for (i in y){
      ifelse(i > 2, 
             z(i) <- b[index, 5],
             ifelse(i == 2, 
                    z(i) <- b[index, 3],
                    ifelse(i == 1, 
                           z(i) <- b[index, 2],
                           ifelse( i == 0, 
                           z(i) <- b[index, 4],
                           z(i) <- b[index, 5]))))
      print(z(i))
    }
  }
  }

这对我来说还是新鲜事。 不知道我哪里错了。 当我分配时:

a$adjusted <- adjust(a$problem, a$score)

什么都没发生

在此非常感谢任何帮助。

为了简化嵌套的 ifelse 语句,我使用了 dplyr 包中的 case_when 函数。我还使用 match 函数来简化内部循环(即 sapply)

a<-read.table(header=TRUE, text="id      score   problem
1       12      1
2       11      6
3       13      2
4       14      0
5       NA      NA")

b<-read.table(header=TRUE, text="score   q   r   s   t
11      12  13  11  NA
12      14  15  12  NA
13      16  20  13  NA
14      18  22  14  NA
NA      NA  NA  NA  NA")

library(dplyr)

#find column name associated with problem score if NA use the score column
colname<-case_when(
    a$problem==0 ~ "s",
    a$problem==1 ~ "q",
    a$problem==2 ~ "r",
    a$problem >2 ~ "t",
    is.na(a$problem) ~"score"
)

# find the corresponding row in table b to match data frame a
rowscore<-match(a$score, b$score)

#column name and rowscore are the same length
#loop through the column name/row name to find the adjusted score
a$adjusted<-sapply(1:length(rowscore), function(i){b[[colname[i]]][rowscore[i]]} )