【发布时间】: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 部分。鉴于它是一个列表,我需要指向列表的某个元素,不仅是列和行,而且我该怎么做呢?毕竟,我希望它在每个元素中完成。有什么想法吗?
【问题讨论】: