0

我正在尝试阅读 R 中的 excel 工作簿,并且每个工作表都会创建一个数据框。

在下一步中,我想读取创建的数据框,并在相应数据框中的每个列之前使用工作表名称和下分。

这是我正在做的事情:

library(readxl)

# Store Sheet Names in a vector
sheet <- excel_sheets("D:/OTC/JULY DATA.XLSX")

# Trim any of the Trailing White Spaces
sheet_trim_trailing <- function (x) sub("\\s+$", "", x)
sheet <- sheet_trim_trailing(sheet)

# Read each of the sheets in the workbook and create a 
# dataframe using respective names of the sheets

for(i in 1:length(sheet)){
  # this read a sheet and create the dataframe using its name
  assign(sheet[i], read.xlsx("DATA.XLSX", sheetIndex = i))
  # store dataframe name into a vector
  sname <- sheet[i]
  # use vector to change the col names in the respective dataframe
  colnames(sname) <- gsub("^", paste0(sname,"_"), colnames(sname))
}

创建了数据框但列名没有改变?

我不知道我错在哪里?

4

2 回答 2

2

你需要做的是类似

colnames(get(sheet[i])) <- gsub("^", paste0(sname,"_"), colnames(get(sheet[i])))

但这会出错

target of assignment expands to non-language object

一种解决方法是使用临时变量来更改列名

可重现的例子

temp <- mtcars[1:5,]
d <- get("temp")
colnames(d) <- sub("y", " ", colnames(d))
assign("temp", d)

尝试这个

for(i in 1:length(sheet)){
  assign(sheet[i], read.xlsx("DATA.XLSX", sheetIndex = i))
  t <- get(sheet[i])
  colnames(t) <- gsub("^", paste0(sheet[i],"_"), colnames(t))
  assign(sheet[i], t)
}
于 2017-08-29T07:24:02.720 回答
1

我想我正在寻找类似的东西,它与上面的功能相同。

试试这个替代方案:

library(readxl)

# function to read all the sheets from excel workbook
read_all_sheets <- function(xlsfile) {
  sheets <- excel_sheets(xlsfile)
  setNames(lapply(sheets, function(.) {
    tbl <- read_excel(xlsfile, sheet = .)
    # this will change the col names with sheet name 
    #  and underscore as prefix
    names(tbl) <- paste(., names(tbl), sep = "_")
    tbl
  }), sheets)
}

## create dataframes from sheets
# first read all the sheets are list
List_of_All_Sheets <- read_all_sheets("Location/of/the/file.xlsx")
# then create dataframes
lapply(names(List_of_All_Sheets), 
       function(nams) assign(nams, List_of_All_Sheets[[nams]], 
                             envir = .GlobalEnv))
于 2017-08-29T10:29:20.590 回答