A subset of the data.frames list and the data.frames returned list

I understand that this question is very similar to this (among others), however I cannot change the solution (s) to fit my problem. Please mark as a duplicate or link to an existing answer, if necessary. Here are some examples slightly modified from the above question:

a=c(1,2,3,4,5,6) b=c(4,5,6,5,5,5) c=c(3,4,5,6,7,8) A=data.frame(a=a,b=b,c=c) B=data.frame(a=c,b=b,c=a) C=data.frame(a=b,b=c,c=a) l <- list(A, B, C) 

I would like to create a list of data frames, which is a subset of the source data (in l ) that matches the condition. For example, I would like to return all values ​​greater than or equal to 4 with lower values ​​replaced by NA , so my new subsetl list looks like this. (I don't care about storing the NA in the right place in the data frame.)

 > subsetl [[1]] abc 1 NA 4 NA 2 NA 5 4 3 NA 6 5 4 4 5 6 5 5 5 7 6 6 5 8 [[2]] abc 1 NA 4 NA 2 4 5 NA 3 5 6 NA 4 6 5 4 5 7 5 5 6 8 5 6 [[3]] abc 1 4 NA NA 2 5 4 NA 6 5 NA 4 5 6 4 5 5 7 5 6 5 8 6 

I hope my example is clear enough to understand, but let me know if not. This is without a doubt the simple use of lapply , sapply or the like, but I cannot get the syntax correctly when using lists, and especially when a list of frame data is the desired result.

+4
source share
1 answer

This should do it for you:

 subsetl <- lapply(l,function(x) { x[x<4] <- NA return(x) }) 

Result:

 >subsetl [[1]] abc 1 NA 4 NA 2 NA 5 4 3 NA 6 5 4 4 5 6 5 5 5 7 6 6 5 8 [[2]] abc 1 NA 4 NA 2 4 5 NA 3 5 6 NA 4 6 5 4 5 7 5 5 6 8 5 6 [[3]] abc 1 4 NA NA 2 5 4 NA 3 6 5 NA 4 5 6 4 5 5 7 5 6 5 8 6 
+4
source

Source: https://habr.com/ru/post/1494266/


All Articles