将lapply与if一起使用以测试列表中的每个元素 [英] Using lapply with if to test each element in a list
本文介绍了将lapply与if一起使用以测试列表中的每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个列表:
alist<- list(4,6,8,9)
我要测试每个列表元素是否大于7,如果列表为true,则返回列表1,如果为false,则返回列表0.
I want test if each list element is greater than 7 and return a list of 1 if its true and 0 if false.
但是我必须使用lapply.
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,"
推荐答案
我很难回答这个问题,因为这样做是非常不明智的.您可以尝试更明确一些,并使用方括号,如下所示:
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})
或矢量化的ifelse
lapply(alist, function(x) ifelse(x > 7, 1, 0))
或者最好的是:
as.numeric(alist > 7)
这篇关于将lapply与if一起使用以测试列表中的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文