簡體   English   中英

R讀取excel文件並選擇特定的行和列

[英]R Read excel file and select specific rows and columns

我想將xls文件讀入R並選擇特定的列。 例如,我只希望第1到10列和第5-700行。我認為您可以使用xlsx進行此操作,但是我不能在使用的網絡上使用該庫。 我可以使用另一個軟件包嗎? 我該如何選擇所需的列和行?

謝謝

既然你是無法帶領xlsx包,你可能要考慮base R和使用read.csv 為此,請將Excel文件另存為csv。 有關如何執行此操作的說明可以在網上輕松找到。 注意,csv文件仍然可以作為Excel打開。

這些是僅讀取第二和第三列和行所需要執行的步驟。

hd = read.csv('a.csv', header=F, nrows=1, as.is=T) # first read headers
removeCols <- c('NULL', NA, NA) #define which columns to keep/remove

df <- read.csv('a.csv', skip=2, header=F, colClasses=removeCols) #skip says which rows not to read
colnames(df) <- hd[is.na(removeCols)]

df

  two three
1   5     8
2   6     9

這是我使用的示例數據。

a <- data.frame(one=1:3, two=4:6, three=7:9)
write.csv(a, 'a.csv', row.names=F)
read.csv('a.csv')

  one two three
1   1   4     7
2   2   5     8
3   3   6     9

您可以嘗試以下方法:

 library(xlsx)
 read.xlsx("my_path\\my_file.xlsx", "sheet_name", rowIndex = 5:700, colIndex = 1:10)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM