【发布时间】:2021-04-01 13:57:21
【问题描述】:
我创建了一个数据框列表。我需要遍历它们,过滤我需要的内容并保存为单个文件。 但是,我需要从每个文件中了解每个值的来源。
每个数据框都有一个名称,例如 Plastic Chair 1111、Wooden Chair 3950、Table 6909 等...并保存在名为“listed”的列表中,该列表包含以下结构:
listed[1]
Material_ID ABC Key.Figure W01 W02 W03
46548970 A Actuals 1048 564 548
46548970 A Forecasted 848 500 590
18969856 A Actuals 358 1500 900
18969856 A Forecasted 460 1602 1000
listed[2]
Material_ID ABC Key.Figure W01 W02 W03
24564897 A Actuals 1258 444 798
26548970 A Forecasted 1345 500 850
34879856 A Actuals 985 1020 980
15486856 A Forecasted 846 1064 1100
我想得到的是:
Group name Group Code Material_ID ABC Key.Figure W01 W02 W03
Plastic Chair 1111 46548970 A Actuals 1048 564 548
Plastic Chair 1111 18969856 A Actuals 358 1500 900
Wooden Chair 3950 24564897 A Actuals 1258 444 798
Wooden Chair 3950 34879856 A Actuals 985 1020 980
是否可以使用数据框名称在左侧创建这两列?
非常感谢您的帮助!
如果您需要更好地了解情况,这是我的代码。
library(openxlsx)
library(dplyr)
library(purrr)
# read the data
filename = 'Dataset.xlsx'
wb <- loadWorkbook(filename)
# get a list of the spreadshits in the excel file
sheetNames <- sheets(wb)
sheetNames <- make_names(sheetNames)
# create an empty list
listed <- list()
# assign which spreadshit as a dataframe inside a list
for(i in 1:length(sheetNames))
{
listed[[i]] <- assign(sheetNames[i],readWorkbook(wb,sheet = i))
print(paste0("read the ", i," file")) # here it says what it's doing
}
# remove variable Sales.Org.ID
map(listed, ~ (.x %>% select(-Sales.Org.ID)))
# filter the dataframes to only show rows with Key.Figure = "Actual Totals"
list_actuals <- lapply(listed, function(x) x %>%
filter( Key.Figure == "Actual Totals"),
)
# put the result in a single dataframe
result_actuals = do.call(rbind,list_actuals)
【问题讨论】:
-
您是否看过
purrr::map_dfr,它适用于使用.id参数附加数据框名称的命名数据框列表? -
如果没有最小的可重现示例,很难提供答案。我会注意到,您现在可以将数据框放在带有列表列的更大数据框的列中。如果您有一列包含数据框的名称,则可以添加一个名为
data的列,其中包含每个数据框,然后变异一个函数来进行过滤,然后在变异列上执行rbind。
标签: r list dataframe spreadsheet