如何处理lapply中的特定单元格? [英] How to address specific cell in lapply?
问题描述
我要升级"我的代码通过使用lapply函数替换使用for循环的mass-import.使用 lapply(list.files(),read.csv)
后,我得到了一个数据帧列表.问题是,数据有点混乱,并且在一个特定的单元格中只提到了一些事情(例如参与者的性别).当我使用for循环时,这不是问题,因为我只能引用特定的单元格.当我使用时:
I want to "upgrade" my code by replacing mass-import using for loop with lapply function. After using lapply(list.files(), read.csv)
I've got a list of dataframes. The problem is, the data is a bit messy and some things (like participant's sex) are mentioned only once, in one specific cell. It wasn't a problem when I used a for loop, as I could just refer to a specific cell. When I used:
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)
每个临时变量看起来像这样:
each temp variable looked like this:
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变量现在是一个列表:
That's what I want. But how can I refer to a certain cell when using lapply? The following code doesn't work, as the temp variable is now a list:
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
部分.给定一个列表,我需要指向列表中的某个元素,不仅是行和列,还应该怎么做?毕竟,我希望在每个元素中都能做到.有什么想法吗?
The slice
and select
functions work all right, the problem lies in the mutate
part. Given it's a list, I need to point to a certain element of the list, not only column and row, but how can I do that? After all, I want it to be done in each element. Any ideas?
推荐答案
您可以:
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中的特定单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!