如何解决 lapply 中的特定单元格?
How to address specific cell in lapply?
我想通过用 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 <- 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
部分。鉴于它是一个列表,我需要指向列表中的某个元素,不仅是列和行,但我该怎么做呢?毕竟,我希望它在每个元素中完成。有什么想法吗?
你可以这样做:
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])
})
我想通过用 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 <- 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
部分。鉴于它是一个列表,我需要指向列表中的某个元素,不仅是列和行,但我该怎么做呢?毕竟,我希望它在每个元素中完成。有什么想法吗?
你可以这样做:
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])
})