Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using lapply with if to test each element in a list

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,"
like image 744
rsgmon Avatar asked Oct 28 '12 19:10

rsgmon


People also ask

Does Lapply return a list?

Format of an lapplylapply returns a list as it's output. In the output list there is one component for each component of the input list and it's value is the result of applying the function to the input component.

How do I apply a function to a list in R?

lapply() function in R Programming Language is used to apply a function over a list of elements. lapply() function is used with a list and performs the following operations: lapply(List, length): Returns the length of objects present in the list, List.

What is the difference between Lapply and Sapply in R?

Difference between lapply() and sapply() functions:lapply() function displays the output as a list whereas sapply() function displays the output as a vector. lapply() and sapply() functions are used to perform some operations in a list of objects.

What does the Lapply function do?

The lapply() function helps us in applying functions on list objects and returns a list object of the same length. The lapply() function in the R Language takes a list, vector, or data frame as input and gives output in the form of a list object.


2 Answers

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)
like image 189
Tyler Rinker Avatar answered Sep 28 '22 10:09

Tyler Rinker


Another two:

lapply(alist > 7, as.integer)

or

lapply(alist > 7, ifelse, 1, 0)
like image 38
DRozen Avatar answered Sep 28 '22 10:09

DRozen