$运算符用于变量对象名称

时间:2018-04-25 13:23:56

标签: r

我正在尝试使用$运算符在可变创建的data.frame对象的for循环中选择和重新格式化特定列。我在注释的代码中尝试了4种不同的解决方案,但它们都不起作用。我看了很多,但我似乎没有找到另一个尝试的解决方案。 如何使用$运算符选择具有可变data.frame名称的特定列?

由于

weather_data_files<-c("CMC","ECMWF","ECMWF_VAR_EPS_MONTHLY_FORECAST",
                          "GFS","ICON_EU","UKMET_EURO4")
for(filename in weather_data_files){

  #create data frame environment objects
  assign(paste(filename),read.csv(file = paste(filename,".csv",sep = ""),sep = ";"))

  #first solution does not work, because filename is here an atomic vector 
  #rather than a data.frame
  #ErrorMessage: $ operator is invalid for atomic vectors
  filename$Forecast.Time<- as.POSIXct(filename$Forecast.Time,
                                      format="%d.%m.%Y %H:%M+%S",tz="UTC")

  #ok get it, let's try second soltution,but
  #it also does not work allthough i try to get the data.frame object
  #ErrorMesssage: could not find function "get<-
  get(filename)$Forecast.Time<-
    as.POSIXct(get(filename)$Forecast.Time,format="%d.%m.%Y %H:%M+%S",tz="UTC")

  #Third solution as.name also does not work
  #ErrorMessage: object of type 'symbol' is not subsettable
  as.name(filename)$Forecast.Time<-
    as.POSIXct(as.name(filename)$Forecast.Time,format="%d.%m.%Y %H:%M+%S",tz="UTC")

  #Fourth solution comparable to second solution, still not working
  #ErrorMessage: could not find function "eval<-"
  eval(assign(filename,get(filename)))$Forecast.Time<-
    as.POSIXct(eval(assign(filename,get(filename)))$Forecast.Time,
                format="%d.%m.%Y %H:%M+%S",tz="UTC")

}

1 个答案:

答案 0 :(得分:3)

所以,问题是你传递的是字符串,而不是对象。 get函数检索对象,只是没有存储它的位置。

您可以随时在循环时将字符串加载到临时变量中。操作临时变量,然后在完成后分配。

for(filename in c("a","b")){
    tmp <- get(filename)
}

您也可以跳过大部分for循环并使用apply系列。

files = lapply(paste(c("CMC","ECMWF","ECMWF_VAR_EPS_MONTHLY_FORECAST",
                      "GFS","ICON_EU","UKMET_EURO4"),".csv",sep=""),
       read.csv,sep=";")
files = lapply(files,function(x){x$Forecast.Time = as.POSIXct(x$Forecast.Time,
               format="%d.%m.%Y %H:%M+%S",tz="UTC");return(x)}

现在您有一份可以处理的文件列表。如果需要,可以将它们分配给全局变量。