Using lapply with if to test each element in a list

前端 未结 2 1329
面向向阳花
面向向阳花 2021-02-04 14:14

Suppose I have a list:

alist<- list(4,6,8,9)

I want test if each list element is greater than 7 and return a list of 1 if its true and 0 if

相关标签:
2条回答
  • 2021-02-04 15:18

    Another two:

    lapply(alist > 7, as.integer)
    

    or

    lapply(alist > 7, ifelse, 1, 0)
    
    0 讨论(0)
  • 2021-02-04 15:20

    It pains me to answer this because it's very un R to do this. You could try being more explicit and use brackets as in:

    lapply(alist, function(x) if (x > 7) {1} else {0})
    

    Or the vectorized ifelse

    lapply(alist, function(x) ifelse(x > 7, 1, 0))
    

    Or best of all:

    as.numeric(alist > 7)
    
    0 讨论(0)
提交回复
热议问题