Reputation: 390
Similar question is answered here
I have a list of data frames (i.e. 1000) that looks like this:
> lst[1000]
$rand1000
Binomial S4 S5 S6
254 Euastacus suttoni 25.816165 4.1916527 86.3
327 Orconectes hobbsi 16.726409 5.5241308 25.0
282 Faxonella creaseri 17.026970 6.4109494 18.0
319 Orconectes durelli 14.093957 7.2342324 35.0
525 Procambarus raneyi 15.799001 6.3746574 55.1
I want to apply function to S4, S5 and S6 columns for all data frames in the list. So I wrote this function:
lapply(lst, function(x) {x$S4 <- sensitivity.rand(x[[2]], 25); x})
(here 'sensitivity.rand' is a function that takes the vector and threshold (in the above code 25 is the threshold) and assign into H or L)
that give the output as (which is good):
$rand1000
Binomial S4 S5 S6
254 Euastacus suttoni H 4.1916527 86.3
327 Orconectes hobbsi H 5.5241308 25.0
282 Faxonella creaseri H 6.4109494 18.0
319 Orconectes durelli H 7.2342324 35.0
525 Procambarus raneyi H 6.3746574 55.1
But if I see that the original data frame is not changed (i.e. it is as it was before). How can I do this. I need to do this for all S4, S5 and S6 columns for all data frame in the list. So that the original data frames will change into like this:
> lst[1000]
$rand1000
Binomial S4 S5 S6
254 Euastacus suttoni H H H
327 Orconectes hobbsi H L H
282 Faxonella creaseri H H L
319 Orconectes durelli H L L
525 Procambarus raneyi H H H
Upvotes: 4
Views: 2011
Reputation: 886968
We need to assign the output back to the list
or create a new object. Also, in the OP's code, the function is only applied to the 2nd column. We can either loop over the columns of interest and apply the function or do it separately
lst <- lapply(lst, function(x) {x[2:4] <- lapply(x[2:4], sensitivity.rand, threshold = 25)
x})
Or if we are using tidyverse
, this can be done with mutate_each
lst <- lapply(lst, function(x) x %>%
mutate_each(funs(sensitivity.rand(., 25)), 2:4))
Upvotes: 3