【问题标题】:How to write a sequential for loop with conditional lookup capability如何编写具有条件查找功能的顺序 for 循环
【发布时间】:2019-08-30 22:10:59
【问题描述】:

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

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

  • 分数(参与者分数)
  • 问题(参与者得分问题)

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

  • 分数(参与者分数)
  • q(问题 = 1 时的调整分数)
  • r(问题 = 2 时的调整分数)
  • s(问题 = 0 时调整后的分数)
  • t(问题> 2时调整分数)

在第一个 for 循环中,我找到了索引 a$score = b$score

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

这里是data.frame a

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

这里是data.frame b

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,使用if (condition) { ... } else { ... }

标签: r function for-loop sapply


【解决方案1】:

为了简化嵌套的 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]]} )

【讨论】:

  • 这正是我所需要的,一个巨大的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
  • 1970-01-01
  • 2023-01-29
  • 1970-01-01
相关资源
最近更新 更多