将函数应用于列表中所有数据框的某些列,然后将值分配给列 [英] apply function to certain columns of all dataframe in list and then assign value to columns
问题描述
在此处
我有一个数据帧列表(即1000个),如下所示:
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
我想对列表中的所有数据帧的S4,S5和S6列应用功能.所以我写了这个函数:
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})
(此处的"sensitivity.rand"是采用 vector 和 threshold (在上面的代码25中是阈值)并分配为H或L的函数)
(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
但是,如果我看到原始数据帧没有更改(即,它像以前一样).我怎样才能做到这一点.我需要对列表中所有数据框的所有S4,S5和S6列执行此操作.这样原始数据帧将变成这样:
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
推荐答案
我们需要将输出分配回 list
或创建一个新对象.同样,在OP的代码中,该功能仅适用于第二列.我们可以遍历感兴趣的列并应用该函数,也可以单独执行
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})
或者如果我们使用的是 tidyverse
,则可以使用 mutate_each
lst <- lapply(lst, function(x) x %>%
mutate_each(funs(sensitivity.rand(., 25)), 2:4))
这篇关于将函数应用于列表中所有数据框的某些列,然后将值分配给列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!