循环与条件子集数据

时间:2017-05-16 12:28:12

标签: r

我正在尝试自动化来自多个dfs的数据子集。首先,我使用简单循环在我的目录中打开所有需要的dfs:

temp=list.files(pattern="*.csv")
for (i in 1:length(temp)) assign(temp[i], read.csv(temp[i]))

将所有文件写为单独的数据框,名称由temp列表指示 我的所有数据集共享结构,使用示例如下所示:

CAR_Brand Fuel_type Year_of_production

CarBrand1   Gas             2014
CarBrand1   Gas             2010
CarBrand1   Gas             2007
CarBrand1   Diesel          2006
CarBrand1   Electric        2013
CarBrand1   Electric        2001
CarBrand2   Electric        2007
CarBrand2   Diesel          2004
CarBrand2   Gas             2009
CarBrand2   Gas             2004
CarBrand2   Electric        2000
CarBrand2   Electric        2001
CarBrand2   Electric        2013
CarBrand2   Diesel          2001
CarBrand2   Diesel          2006
CarBrand2   Gas             2010
CarBrand2   Gas             2002
CarBrand2   Gas             2012
CarBrand2   Electric        2009
CarBrand3   Gas             2013
CarBrand3   Gas             2009
CarBrand3   Gas             2015
CarBrand3   Gas             2007
CarBrand3   Diesel          2000
CarBrand3   Diesel          2013

让我们说每个df的名字都是这样的:Cardf1.csv,Cardf2.csv,Cardf3.csv(.csv是由第一个代码生成的,我不介意)

我希望根据某些条件对某些行进行子集化,然后将它们写成具有新名称的新数据集(比如Cardf1.csv_electric2,Cardf2.csv_electric2等)我意识到我可以用与我使用的代码非常相似的方式实现它打开我的数据。首先,我创建了新文件的名称列表:

for(i in 1:length(temp)){
  newtemp[i]=paste(temp[i],"_gdp",sep="")

然后我写了非常简单的自定义函数,使我的循环更容易。我用两个版本写了它:

custofun1=function(x){
subset(x, x$Car_Brand %in% "CarBrand2" & x$Fuel_Type %in% "Electric")}

customfun2=function(x){
subset(x, x[,1] %in% "CarBrand2" & x[,2] %in% "Electric")}

然后将其置于循环中:

  for(i in 1:length(temp)){
  assign(newtemp[i],customfun(temp[i]))}

注意我写了customfun,因为它适用于两者。每个都会产生不同的错误:

  customfun1:
  Error in x$Car_Brand : $ operator is invalid for atomic vectors

  customfun2:
  Error in x[, 1] : incorrect number of dimensions 

所以我认为这个问题存在于我的数据子集方法中,但我发现它是基于非数字变量的subset最方便的方法。是否有可能以这种方式工作或需要采用不同的方法?

0 个答案:

没有答案
相关问题