操作列表中的文件的问题

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

我通过创建目录(dir)和使用(lapply)导入了90个excel文件。我不确定这是否被称为嵌套列表。在列表中导入excel文件后,我可以看到一些文件有四列,其他一些文件有五列。我的问题是:

  1. 如何从此列表中删除包含四列的文件并将其粘贴到新列表中。
  2. 然后,我如何将列表中的所有类似列文件合并到一个文件中。
  3. 如何将这两个文件保存为两个不同的Excel工作表?
library(foreign)
setwd("F:\\Spring 2019\\Thesis_data\\Kam_Thesis\\data\\nontidal_water_level")

nontidal_list <- dir(pattern= ".xlsx")

nontidal_water_level <- lapply(nontidal_list, read_excel)
r lapply xlsx
2个回答
0
投票

由于您没有提供示例数据集,我们假装它看起来像这样:

> nontidal_water_level <- lapply(1:4, function(i) data.frame(matrix(1:12 * i, ncol = 3 + (i %% 2))))
> str(nontidal_water_level)
List of 4
 $ :'data.frame':   3 obs. of  4 variables:
  ..$ X1: int [1:3] 1 2 3
  ..$ X2: int [1:3] 4 5 6
  ..$ X3: int [1:3] 7 8 9
  ..$ X4: int [1:3] 10 11 12
 $ :'data.frame':   4 obs. of  3 variables:
  ..$ X1: int [1:4] 2 4 6 8
  ..$ X2: int [1:4] 10 12 14 16
  ..$ X3: int [1:4] 18 20 22 24
 $ :'data.frame':   3 obs. of  4 variables:
  ..$ X1: int [1:3] 3 6 9
  ..$ X2: int [1:3] 12 15 18
  ..$ X3: int [1:3] 21 24 27
  ..$ X4: int [1:3] 30 33 36
 $ :'data.frame':   4 obs. of  3 variables:
  ..$ X1: int [1:4] 4 8 12 16
  ..$ X2: int [1:4] 20 24 28 32
  ..$ X3: int [1:4] 36 40 44 48

对于问题1,您可以通过循环并使用ncol找到每个列的列,然后将具有相同列数的数据帧放入单个列表中:

> ncolumns <- lapply(nontidal_water_level, ncol)
> nontidal_3col <- nontidal_water_level[ncolumns == 3]
> nontidal_4col <- nontidal_water_level[ncolumns == 4]

对于问题2,您可以在每个列表的所有元素上调用rbind

> (nontidal_3col <- do.call(rbind, nontidal_3col))
  X1 X2 X3
1  2 10 18
2  4 12 20
3  6 14 22
4  8 16 24
5  4 20 36
6  8 24 40
7 12 28 44
8 16 32 48
> (nontidal_4col <- do.call(rbind, nontidal_4col))
  X1 X2 X3 X4
1  1  4  7 10
2  2  5  8 11
3  3  6  9 12
4  3 12 21 30
5  6 15 24 33
6  9 18 27 36

最后,对于问题3,你可以使用像writexl这样的包,但我建议你把它写成.csv

write.csv(nontidal_3col, "my_3_column_file.csv")
write.csv(nontidal_4col, "my_4_column_file.csv")

0
投票

您可以创建一个完成工作的循环。

这三个步骤:

if!require(plyr) install.packages(plyr) 
df_4col <- data.frame() # a dataframe that after function must contain all four columns data
df_5col <- data.frame() # the same eith five colums
df_4list <- c() # a list with the filenames
df_5list <- c() # a list with the filenames

for (i in 1:length(nontidal_list)){
df <- read_excel(nontidal_list[i])
if (length(df)==4) {
    df_4col<-plyr::rbind.fill(df_4col, df) 
    df_4_list<-append(df_4list, nontidal_list[i]} else
if (length(df)==5) {
    df_5col<-plyr::rbind.fill(df_4col, df) 
    df_5list<-append(df_5list, nontidal_list[i]} 
}
© www.soinside.com 2019 - 2024. All rights reserved.