作者peiwinds (Macchiato Caramel)
看板R_Language
标题[问题] 一次读入多个csv file
时间Fri Apr 18 09:42:42 2014
[问题类型]:
程式谘询(我想用R 做某件事情,但是我不知道要怎麽用R 写出来)
[软体熟悉度]:
语法不太熟
[问题叙述]:
最近因为要处理的资料很多,想一次读入多个csv档 (数十个到数百个都有)
并且将这些档案已 data frame的方式 rbind起来
下面第一个是我在 stackoverflow看人家分享拿来用的
第二个是我自己後来写的
[程式范例]:
1.
temp <- do.call(rbind, lapply(list.files(path=".", pattern="*.csv"),
read.table, header=TRUE, sep=","))
# 方法一的问题在於他的path我
无法指定我要的目录 例如 D:/test 目录
# 该目录中明明有csv档,但是却会出现错误讯息如下
# Error in file(file, "rt") : cannot open the connection
# 当然如果我把资料都丢在环境目录下,当然是都读得到也不会有问题
# 因此我便写了第2种
2.
path <- "D:/test/"
files <- list.files(path=path, pattern="*.csv")
bindtemp <- data.frame()
temp <- data.frame()
for (file in files) {
bindtemp <- read.csv(paste(path,file,sep=""))
temp <- rbind(temp,bindtemp)
}
# 想问的是第一种的写法为什麽不能指定目录
# 第二个只是丢上来跟大家分享,看有什麽什麽改进的空间XD
[关键字]:
读入多个外部档案
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 140.96.100.10
※ 文章网址: http://webptt.com/cn.aspx?n=bbs/R_Language/M.1397785365.A.6AD.html
1F:→ obarisk:第一种可以指定路径啊 04/18 10:58
2F:→ gsuper:Dir <- paste("./",system("ls",intern=TRUE),sep="") 04/18 19:54