order()函数:错误“顺序错误(产品$ var):参数1不是向量”

时间:2015-06-24 00:00:31

标签: r

我在互联网上搜索过很多但我没有找到解决问题的方法。我的代码非常简单。我希望函数使用提供的“字符”按列名称data.frame"character"进行排序。我目前的职能是:

products=as.data.frame(read.csv("cameras.csv", sep=",", header=T))

ascending=function(var){  
  products_ascending = products[order(products[[var]]),] 
  rownames(products_ascending) <- NULL
  return(products_ascending)
}

ascending(Resolution)

head(products)

  Resolution Zoom   Size Price Screen   Video Settings Sensitivity

1            12     24.0  98.45   750 461000 2073600       20        3200

2         12 26.0 129.11   699 460000 2073600       19        3200

3         16 12.0  55.10   449 460800 2073600       12        3200

4         10 10.7  56.25   290 307500  921600       17        3200

5         12  4.0  53.48   499 460000 2073600        6        3200

6         14 18.0  86.64   138 230000  921600       12        6400

我用products_ascending = products[order(products[[var]]),]

修复了它

是的它有效,但在函数中没有返回错误:

  

(function(x,i,exact)if(is.matrix(i))as.matrix(x)[[i]] else .subset2(x,:
)出错     对象“未找到解决方案”

dput(head(products))

structure(list(Resolution = c(12, 12, 16, 10, 12, 14), Zoom = c(24, 
26, 12, 10.7, 4, 18), Size = c(98.45, 129.11, 55.1, 56.25, 53.48, 
86.64), Price = c(750L, 699L, 449L, 290L, 499L, 138L), Screen = c(461000L, 
460000L, 460800L, 307500L, 460000L, 230000L), Video = c(2073600L, 
2073600L, 2073600L, 921600L, 2073600L, 921600L), Settings = c(20L, 
19L, 12L, 17L, 6L, 12L), Sensitivity = c(3200L, 3200L, 3200L, 
3200L, 3200L, 6400L)), .Names = c("Resolution", "Zoom", "Size", 
"Price", "Screen", "Video", "Settings", "Sensitivity"), row.names = c(NA, 
6L), class = "data.frame")

2 个答案:

答案 0 :(得分:4)

请参阅此article,其中说明了子集功能([[[$)的工作原理。

您需要使用products[[var]]

引用Hadley Wickham的文章的相关部分,

“$是一个速记运算符,其中x $ y相当于x [[”y“,exact = FALSE]]”。

答案 1 :(得分:2)

我的猜测(我们需要查看您的数据),您是否需要使用不同的子集方法:

ascending=function(var){  
  products_ascending = products[order(products[[var]]),]            
  return(products_ascending)
}

您不能使用$和在其后添加的变量进行子集化。

然后:

ascending("Resolution")