Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用变量作为列名对数据帧进行排序_R - Fatal编程技术网

R 使用变量作为列名对数据帧进行排序

R 使用变量作为列名对数据帧进行排序,r,R,我有两个数据帧,我想分别按其最后一列排序,我已经尝试了一段时间,但没有成功,主要思想是创建一个函数,以避免对每个数据帧重复执行此操作,我正在构建的函数如下: order_dataF = function(x){ tCol = colnames(x[length(x)]) print(tCol) #x <- x[with(x, order(-tCol),)] #x <- x[with

我有两个数据帧,我想分别按其最后一列排序,我已经尝试了一段时间,但没有成功,主要思想是创建一个函数,以避免对每个数据帧重复执行此操作,我正在构建的函数如下:

    order_dataF = function(x){
            tCol = colnames(x[length(x)])
            print(tCol)
            #x <- x[with(x, order(-tCol),)]
            #x <- x[with(x, order(-(paste(tCol))),)]
            #x[do.call( order, x[,match(tCol,names(x))]),]
            #x <- x[order(x$tCol),]
    }
我正在打印tCol以查看它是否真的包含最后一个列名,在本例中,它确实包含我需要的内容

也许这是一个愚蠢的问题,解决起来太容易了,但我无法前进,因为这会拖我的后腿,我很沮丧


此外,我看到这看起来像是重复的,但事实并非如此,没有人在问正确的问题(甚至可能不是我),但想法是“为我的字符串变量的内容排序,该字符串变量是从数据框列名中获得的”

通常,不要尝试将
或其他“非标准”一起使用函数内部的求值函数,如
子集

order_by_last_col = function(df) {
    df[order(df[, ncol(df)]), ]
}

# test
order_by_last_col(mtcars)
如果使用存储为字符串的列名,必须使用
[
,而不是
$
,因为
$
也是一种非标准的求值快捷方式,而且它从不求值
$
之后的代码,它只会查找具有该确切名称的列。如果您更愿意使用名称而不是索引(如上所述),使用
[
按此方式执行:

order_by_last_col = function(df) {
    last_col_name = tail(names(df), 1)
    df[order(df[, last_col_name]), ]
}
编辑:再做几个实验,看看你最初的尝试为什么不起作用。它们不需要在函数中不起作用,它们只是永远不起作用

col = "wt"
mtcars$col # NULL
with(mtcars, head(col)) # "wt"
mtcars[, match(col, names(mtcars))] # this does work but is unnecessarily long
mtcars[, col] # works, easy
mtcars[[col]] # also works

谢谢Gregor!这终于起到了应有的作用!我找不到任何容易消化的来源来理解这一点。非常感谢!
col = "wt"
mtcars$col # NULL
with(mtcars, head(col)) # "wt"
mtcars[, match(col, names(mtcars))] # this does work but is unnecessarily long
mtcars[, col] # works, easy
mtcars[[col]] # also works