导入多个xlsx文件并从单元格中添加变量,同时跳过行(R)

问题描述 投票:0回答:1

我有多个Excel文件,其中文件的一个关键变量在B2单元格中,但其余数据在其下面的行和列中。

我可以用下面的代码提取 "源 "变量。

all_posts <- map_dfr(files, read_xlsx, range = "B2", col_names = "source")

但是,我还需要获取B2单元格下面的表内的额外数据 用这样的代码。

all_comments <- map_dfr(files, read_xlsx, skip = 5) #I need to skip five rows to where the data table starts.

我如何才能做到让每一批注释都对应B2单元格中的 "源 "变量?基本上,每个Excel文件都是一个 "帖子",在B2单元格中命名,它包含了下面几行帖子的对应评论。

编辑:我添加了其中一个Excel文件的截图,以更好地帮助理解我的问题。enter image description here

r mapping tidyverse purrr readxl
1个回答
1
投票

我能想到的一种方法是使用嵌套的tibbles。我不熟悉 read_xlsx: 我喜欢 read.xlsx 来自 openxlsx 包,但我想你已经明白了。

library(tidyverse)

tibble(file_name = files) %>%
  mutate(post = map_chr(file_name, ~openxlsx::read.xlsx(.x, rows = 2, cols = 2, colNames = FALSE)[1,1],
         data = map(file_name, ~openxlsx::read.xlsx(.x, startRow = 6))
© www.soinside.com 2019 - 2024. All rights reserved.