R:由group定义的两种不同场景的ifelse语句

时间:2014-09-11 13:33:57

标签: r if-statement plot

我有一个示例数据框,我想有条件地绘制(两个不同的绘图场景,唯一的区别是x轴的范围定义)。

 xy <- data.frame(NAME=c("NAME1", "NAME1","NAME1","NAME1","NAME2","NAME2","NAME2"),ID=c(47,47,47,47,259,259,259),YEAR=c(1932,1942,1965,1989,2007,2008,2014),VALUE=c(0,NA,-6,-16,0,-9,-28))

为此,我试图补充ifelse()声明,但我无法弄清楚如何使其与我的两个情节循环兼容。

我尝试做的是以下内容:我生成的不同图表除以组(ID)。

# split data by index 
   ind <- split(x = xy,f = xy[,'ID'])

如果在一个小组中,只有YEAR只能在1946年到2014年之间,那么情节1应该被执行。

# If the values in a group lie ONLY between YEAR 1946 and 2014 and not lower than 1946
    if(xy$YEAR > 1946 & xy$YEAR < 2014) { # <- this needs to be corrected
    ### PLOT Scenario 1 
    for(i in 1:length(ind)){
      png(names(ind[i]), width=1679, height=1165, res=150)
      par(mar=c(6,8,6,5))
      plot(x = c(1946, 2014),
           y = range(ind[[i]][,'VALUE']),
           type='b',
           main=ind[[i]][1,'NAME'],     
        dev.off() 
    }

如果组中包含1946下的YEAR,则应执行Plot Scenario 2。

else{
  ### PLOT Scenario 2 (plot with automatic axis range when also YEARs under 1946 are in a group)
  for(i in 1:length(ind)){
    png(names(ind[i]), width=1679, height=1165, res=150)    
    par(mar=c(6,8,6,5))
    plot(ind[[i]][,c('YEAR','VALUE')],
         type='b',
         main=ind[[i]][1,'NAME'],
    dev.off()  
  }
}

如何在每个组中指定YEAR以在if语句中正确引入它?

2 个答案:

答案 0 :(得分:0)

如果你想在ifelse中这样做,你可以将你的循环包装在函数中,然后调用它们......

所以你会说

 ifFunction<-function(ind){
     for(i in 1:length(ind)){
         png(names(ind[i]), width=1679, height=1165, res=150)
         par(mar=c(6,8,6,5))
         plot(x = c(1946, 2014),
               y = range(ind[[i]][,'VALUE']),
               type='b',
               main=ind[[i]][1,'NAME'],     
         dev.off() 
    }
}

elseFunction<-function(ind){
    for(i in 1:length(ind)){
        png(names(ind[i]), width=1679, height=1165, res=150)    
        par(mar=c(6,8,6,5))
        plot(ind[[i]][,c('YEAR','VALUE')],
             type='b',
             main=ind[[i]][1,'NAME'],
        dev.off()  
  }
}

然后拨打你的ifelse

ifelse(xy$YEAR > 1946 & xy$YEAR < 2014, ifFunction(ind), elseFunction(ind))

快速回答,希望我没有错过任何东西!

答案 1 :(得分:0)

为了便于阅读,我将创建两个绘图功能,每个场景一个(这是可选的)。

plot1 <- function(x) {
  fname <- paste0(x[1, 'ID'], '.png')
  png(fname, width=1679, height=1165, res=150)
  par(mar=c(6,8,6,5))
  plot(x = c(1946, 2014),
       y = range(x$VALUE),
       type='b',
       main=x[1, 'NAME'])     
  dev.off()
}

plot2 <- function(x) {
  fname <- paste0(x[1, 'ID'], '.png')
  png(fname, width=1679, height=1165, res=150)    
  par(mar=c(6,8,6,5))
  plot(x[,c('YEAR','VALUE')],
    type='b',
    main=x[1, 'NAME'])
  dev.off() 
}

然后将此函数应用于ind中的每个项目:

lapply(ind, function(x) ifelse(any(x$YEAR < 1946), plot2(x), plot1(x))