0

我是 R 编程的初学者(使用它进行数据分析)

我有以下数据。(精简版)

state   storeid sales
CA  1   40,000  
CA  2   44,000  
CA  3   38000   
MN  1   26000   
MN  2   25500   

我需要一个返回表现最佳/表现不佳的商店的函数。

我写了以下函数。

storeinfo<-function(num="top") {

  df<-read.csv("store.csv")

  bestVal <- 1;
  if (!missing(num)) {
    if(is.numeric(num)){
      bestVal =  as.numeric(num);
    }
    if(num=="top"){
      bestVal <-1
    }
    if ( num=="poor"){
      bestVal<-0
    }
  }
  print(bestVal)
    data2<-subset(df[,c(1,2,3)])
    data2<-data2[order(as.numeric( data2$sales), data2$storeid,na.last=TRUE,decreasing=TRUE), ]
    idx<-tapply(1:NROW(data2),data2$state,"[",bestVal)
    idx1<-tapply(1:NROW(data2),data2$state,"[",1)

    return (data.frame(data2[idx1,1],data2[idx,2:3]))

}

当我执行上述功能时,我看到以下内容

> head(storeinfo(1))
[1] 1
  data2.idx1..1. storeid  sales
2             CA       2 44,000
4             MN       1  26000

a)如何抑制第一列 2,4 等?(索引) b)如何找到销售额低的商店?c) 如何为返回的数据框设置不同的列名。

4

1 回答 1

0

做这个

min_max_sales = c(which.min(df$sales), which.max(df$sales)) # return row numbers
df[min_max_sales,]

更新。

如果您需要对数据框进行排序并获得销售额排名第 n 的商店,这是使用plyr包的更好方法

plyr::arrange(df, sales)[n,]
于 2013-01-21T17:31:11.003 回答