【问题标题】:How to address specific cell in lapply?如何处理 lapply 中的特定单元格?
【发布时间】:2021-04-25 10:03:09
【问题描述】:

我想通过用 lapply 函数替换使用 for 循环的批量导入来“升级”我的代码。使用lapply(list.files(), read.csv) 后,我得到了一个数据框列表。问题是,数据有点混乱,有些事情(比如参与者的性别)只在一个特定的单元格中被提及一次。当我使用 for 循环时这不是问题,因为我可以只引用一个特定的单元格。我用的时候:

for (x in list.files()) {
temp <- read.csv(x)
temp %>% slice(4:11) %>% select(form_2.index, form_2.response) %>% mutate(sex = temp[1,4])
#temp[1,4] is the one cell where the participant's sex is mentioned
database <- rbind(datadase, temp)

每个临时变量如下所示:

  form_2.index form_2.response sex$form.response
         <dbl> <chr>           <chr>             
1            1 yes             male         
2            2 no              male         
3            3 no              male         
4            4 yes             male         
5            5 yes             male         
6            6 yes             male         
7            7 no              male         
8            8 no              male         

这就是我想要的。但是在使用 lapply 时如何引用某个单元格?以下代码不起作用,因为 temp 变量现在是一个列表:

temp <- lapply(list.files(), read_csv())
temp %>% lapply(slice, 4:11) %>% lapply(select, form_2.index, form_2.response) %>% lapply(mutate, plec = temp[1,4])

slice 和select 函数工作正常,问题出在mutate 部分。鉴于它是一个列表,我需要指向列表的某个元素,不仅是列和行,而且我该怎么做呢?毕竟,我希望它在每个元素中完成。有什么想法吗?

【问题讨论】:

    标签: r lapply


    【解决方案1】:

    你可以这样做:

    library(dplyr)
    
    temp <- lapply(list.files(), function(x) {
      tmp <- readr::read_csv(x)
      tmp %>%
        slice(4:11) %>% 
        select(form_2.index, form_2.response) %>% 
        mutate(sex = tmp[1,4])
    })
    

    【讨论】:

    • 这很聪明,谢谢。您能否解释为什么结果是 tmp 变量,而我不需要做任何类似return(tmp) 或类似的事情;告诉函数它应该返回什么?
    • 您可以这样做,但这不是必需的。如果您在函数中没有明确的return,则默认情况下会返回最后一行存在的任何内容。
    猜你喜欢
    • 2017-03-23
    • 1970-01-01
    • 2013-09-21
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多