0

I have a list of 20 sub-lists named pval, each sub-list pval[[i]] contains several columns. I want to add a new column pval[[i]]$class to mark whether the element of vector causal_snp appears in the column X4 of each sub-list, if yes, mark 1 in the new column, else 0.

for (i in 1:20){
  pval[[i]]$class = ifelse(pval[[i]]$X4 %in% causal_snp, 1, 0)
  pval[[i]]$class = as.factor(pval[[i]]$classe)
}

The loop above works well, but I'd like use the function lapply instead of for loop, here is what I've tried, but the output contains only the new column for each sub-list:

pval_bis <- lapply(pval, function(x) x$classe=ifelse(x$X4 %in% causal_snp, 1, 0))

What can I modify in lapply function to keep all my columns in sub-list and add the new column in each sub-list? Thanks.

Lily
  • 37
  • 6
  • Can you provide data for a reproducible example? http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – DeveauP Apr 26 '16 at 09:13

1 Answers1

1

If we are using lapply, create the column with transform

lapply(pval, transform, classe = as.integer(X4 %in% causal_snp))

In the OP's code, after the assignment, we need to return x

 lapply(pval, function(x) {x$classe=ifelse(x$X4 %in% causal_snp, 1, 0);x})
akrun
  • 874,273
  • 37
  • 540
  • 662