如何使用if嵌套循环

丹尼

编辑:这个问题已经成功回答。

我有一个称为hispn的数据帧和一个称为qq_hispn的五分位数向量。Hispn有两列名为“ FAMINC17”的利息,它们是家庭收入,另外还有“兴奋剂”。

我正在尝试创建一个名为“ Stim_Income”的新列,该列对于5个收入范围以及它们是否处于刺激状态具有不同的值。因此,如果它们在收入范围的0-20%之间,并且使用兴奋剂,则值为1。如果不使用兴奋剂,则值为6。对于20-40%,3和3,值应分别为2和7。 8表示40-60%,依此类推。这将使我能够计算出每个五分位数的处方患病率(1 / 6、2 / 7等)。

我想出了一种非常业余的方法。谁能告诉我为什么它不起作用?

  for (i in 1:5) {
    for (j in nrow(hispn)) {
      if ( (hispn[j,"FAMINC17"]>qq_hispn[i])&&(hispn[j,"FAMINC17"]<=qq_hispn[i+1])&&(hispn[j,"Stimulants"]==1) ) {
        hispn[j,"Stim_Income"]<-i
      } else if ( (hispn[j,"FAMINC17"]>qq_hispn[i])&&(hispn[j,"FAMINC17"]<=qq_hispn[i+1])&&(hispn[j,"Stimulants"]==0) ) {
        hispn[j,"Stim_Income"]<-(i+5)
      }
    }
  }

我试图实现Michelle在注释中链接的代码,但返回了错误。

  hispn %>% 
    mutate(Stim_Income = case_when (
      FAMINC17>qq_hispn[1] & FAMINC17<=qq_hispn[2] & Stimulants==1  ~ 1
      FAMINC17>qq_hispn[1] & FAMINC17<=qq_hispn[2] & Stimulants==0  ~ 6
      FAMINC17>qq_hispn[2] & FAMINC17<=qq_hispn[3] & Stimulants==1  ~ 2
      FAMINC17>qq_hispn[2] & FAMINC17<=qq_hispn[3] & Stimulants==0  ~ 7
      FAMINC17>qq_hispn[3] & FAMINC17<=qq_hispn[4] & Stimulants==1  ~ 3
      FAMINC17>qq_hispn[3] & FAMINC17<=qq_hispn[4] & Stimulants==0  ~ 8
      FAMINC17>qq_hispn[4] & FAMINC17<=qq_hispn[5] & Stimulants==1  ~ 4
      FAMINC17>qq_hispn[4] & FAMINC17<=qq_hispn[5] & Stimulants==0  ~ 9
      FAMINC17>qq_hispn[5] & FAMINC17<=qq_hispn[6] & Stimulants==1  ~ 5
      FAMINC17>qq_hispn[5] & FAMINC17<=qq_hispn[6] & Stimulants==0  ~ 10
  
     )
    )  

另一个用户要求可重现的数据和示例输出。

  m1<- matrix(0,ncol=2,nrow=5)
  m1[1,1]=1000
  m1[2,1]=1000
  m1[3,1]=1000
  m1[4,1]=1000
  m1[5,1]=10000
  m1[3,2]=1

     [,1] [,2]
[1,] 1000    0
[2,] 1000    0
[3,] 1000    1
[4,] 1000    0
[5,] 10000    0

然后,这是新列,其中包含感兴趣的信息(如果for循环可以运行的话)。但是,相反,我得到了NA一栏。

     [,1] [,2] [,3]
[1,] 1000    0    6
[2,] 1000    0    6
[3,] 1000    1    5
[4,] 1000    0    6
[5,]    0    0    7
打字员

根据您提供的一些详细信息,我创建了一个样本数据集。它与五分位数向量并不完全像您的数据,但这是我的尝试:

library(dplyr)

FAMINC17 <- c('0-20','0-20','20-40', '20-40', '40-60', '40-60', '60-80', '60-80', '80-100', '80-100')
Stimulants <- c(1, 0, 1, 0, 1, 0, 1, 0, 1, 0)

hispn <- data.frame(FAMINC17, Stimulants)

hispn %>% 
  mutate(Stim_Income = case_when(
    FAMINC17 == "0-20"   & Stimulants == 1 ~ 1,
    FAMINC17 == "0-20"   & Stimulants == 0 ~ 6,
    FAMINC17 == "20-40"  & Stimulants == 1 ~ 2,
    FAMINC17 == "20-40"  & Stimulants == 0 ~ 7,
    FAMINC17 == "40-60"  & Stimulants == 1 ~ 3,
    FAMINC17 == "40-60"  & Stimulants == 0 ~ 8,
    FAMINC17 == "60-80"  & Stimulants == 1 ~ 4,
    FAMINC17 == "60-80"  & Stimulants == 0 ~ 9,
    FAMINC17 == "80-100" & Stimulants == 1 ~ 5,
    FAMINC17 == "80-100" & Stimulants == 0 ~ 10,
  ))

希望这行得通。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章