如何处理if语句中的NA或NULL值?

时间:2015-10-22 07:34:22

标签: r

我有一个数据集allProductPrice,如下所示:

#data
allProductPrice <- read.table(text="OrderYear  Product   Price
2013       RP110    1790.00000
2014       RP110    1195.08511
2013       RP111    726.77000
2012       EI25     400.15221
2013       EI25     440.89647
2014       EI25     368.97858
2013       FG26     151.09750
2014       FG26     383.09938
2012       RB30     619.70698
2013       RB30     642.82010
2014       RB30     695.00977", header=TRUE)

我想将价格分为不同的价格水平Price4(1500-2000)Price3(1000-1500),Price2(500-1000),Price1(0-500)并获得表priceLevel。< / p>

Year  Price1 Price2 Price3 Price4
2012  1        1      0      0
2013  3        2      0      1
2014  3        1      1      0

我的逻辑:首先获得所有年份和产品,然后使用嵌套循环来定位每个产品的价格,然后按年数和价格水平计算。这是我的代码:

#get the year and product
validYears<-unique(allProductPrice$OrderYear)
AllPRID<-unique(allProductPrice$Product)
AllPRID<-as.character(AllPRID)

#create a new table for Price levels
priceLevel<-data.frame(Year=validYears,Price1=0,Price2=0,Price3=0,Price4=0)

#inital value for UP
UP<-0

#start the loop
for (year in validYears) {
  for(PrId in AllPRID){
      UP<-allProductPrice$Price[allProductPrice$OrderYear==year&allProductPrice$Product==PrId]

    if(is.na(UP)==TRUE&&is.null(UP)==TRUE){
         print("NULL")
  } else if(UP<500){
      priceLevel$Price1[priceLevel$Year==year]<-priceLevel$Price1[priceLevel$Year==year]+1
  }  else if(UP>500&&UP<1000) {
    priceLevel$Price2[priceLevel$Year==year]<-priceLevel$Price2[priceLevel$Year==year]+1
  }  else if(UP>1000&&UP<1500)  {
      priceLevel$Price3[priceLevel$Year==year]<-priceLevel$Price3[priceLevel$Year==year]+1
  }  else {
        priceLevel$Price4[priceLevel$Year==year]<-priceLevel$Price4[priceLevel$Year==year]+1
  } 
  }}

我总是收到错误消息,例如

Error in if (UP < 500) { : argument is of length zero

如何解决这个问题?

2 个答案:

答案 0 :(得分:4)

您可以尝试:

<label>Location Type:</label>
<form:radiobuttons path="StoreLocationType" 
    items="${store_location_types}" itemLabel="displayName" />

答案 1 :(得分:3)

使用cut()功能:

#using cut create groups
allProductPrice$Group <- 
  paste0("Price",
         cut(allProductPrice$Price, 
             c(0, 500, 1000, 1500, 2000),
             c(1, 2, 3, 4)))

#result - use table then convert to a data.frame
as.data.frame.matrix(
  table(allProductPrice$OrderYear, allProductPrice$Group))


#      Price1 Price2 Price3 Price4
# 2012      1      1      0      0
# 2013      2      2      0      1
# 2014      2      1      1      0
相关问题