【问题标题】:How to make for-loop to neglect several columns and do rbind all sheets (regardless the total amount of sheets) in an excel file如何使for循环忽略几列并在excel文件中执行rbind所有工作表(不管工作表的总量)
【发布时间】:2019-05-24 02:07:27
【问题描述】:

我想在 for 循环中执行几个命令

  1. 忽略列下的第一行
  2. 将所有列名更改为小写并消除单词之间的所有空格(如果有的话)
  3. 忽略几列并保留其余列
  4. 对 excel 文件中的所有工作表执行 rbind

我已经这样做了

library(tidyverse)
library(readxl)
library(xlsx)
library(reshape2)
setwd("D:/Plan")
file<-"Plan.xlsx"
excel_sheets(file)
sheet=excel_sheets(file)

for (i in 1:1) {
    file=read_excel(file, sheet=sheet[i])
    file<-file[-1,]
    judul=colnames(file)
    judul=tolower(judul)
    judul=gsub(' ','',judul)
    colnames(file)=judul
    file %>% filter(!is.na(promo))
    file=file %>% filter(!is.na(promo))
    data=file[,names(file) %in% c("promo","startdate","enddate","sku","marketplacename","diskon","stok")]
}

out=data

for (i in 2:2) {
    file=read_excel(file, sheet=sheet[i])
    file<-file[-1,]
    judul=colnames(file)
    judul=tolower(judul)
    judul=gsub(' ','',judul)
    colnames(file)=judul
    file %>% filter(!is.na(promo))
    file=file %>% filter(!is.na(promo))
    data=file[,names(file) %in% c("promo","startdate","enddate","sku","marketplacename","diskon","stok")]
    x<-data
    out=rbind(out,x)
}

此代码只是包含 2 张工作表的文件 excel 的示例。真正的文件是一个有几张纸的文件,但我想做这些订单而不管纸的数量,所以我不会每次在文件中找到不同数量的纸时都编辑脚本。如何做到这一点?

【问题讨论】:

  • 你为什么不做length(excel_sheet(filename))并从1循环到这个号码?然后将结果保存在一个列表中并在循环外 rbind。
  • 怎么办? x
  • 我回答了

标签: r for-loop


【解决方案1】:

我会做这样的事情,我直接迭代工作表名称而不是使用索引。无法保证此代码将直接工作,因为您没有给我们任何示例数据来测试。不过,它应该会为您指明正确的方向,并且可能会通过一些小的调整来工作:

library(readxl)
library(stringr) # Needed for `str_*` functions.
library(dplyr)
library(magrittr) # Needed for `set_colnames`.

file_name <- "Plan.xlsx"
sheets <- excel_sheets(file_name)
df_final <- tibble()

for (sheet in sheets){
    df_final <- read_excel(file_name, sheet = sheet) %>%
        select(-1) %>% 
        set_colnames(str_remove_all(names(.), "\\s") %>% str_to_lower()) %>%  
        filter(!is.na(promo)) %>%
        select(promo, startdate, enddate, sku, marketplacename, diskon, stok) %>% 
        bind_rows(df_final, .)
}

stringr 函数并非绝对必要。我发现命名约定在稍后解释我的代码时很有用,但如果您更喜欢它们,可以坚持使用 gsubtolower。如果您选择的列是连续的,您可以缩短内容,即如果您想要的所有其他列都在这两者之间,您可以执行promo:stok。函数set_colnames 来自magrittr,并提供了colnames(df) &lt;- some_names 的简洁、可链接的替代方案。其余部分或多或少与您的代码相似,只是稍微清理了一下。

【讨论】:

  • tibble() 函数是干什么用的?
  • @NicodemusSigitSutanto tibble 函数创建了一种特殊类型的数据框,而 df_final &lt;- tibble() 我只是创建了一个空数据框。
猜你喜欢
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-29
  • 1970-01-01
相关资源
最近更新 更多