Using lapply with if to test each element in a list

大兔子大兔子 提交于 2020-06-09 12:56:09

问题


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 false.

However I must use lapply.

lapply(alist,if,>7,1) or lapply(alist,if,cond>7,1)

Of course none of these work and I keep getting the following error.

Error: unexpected ',' in "lapply(alist, if,"

回答1:


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)



回答2:


Another two:

lapply(alist > 7, as.integer)

or

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


来源:https://stackoverflow.com/questions/13112316/using-lapply-with-if-to-test-each-element-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!