でそのようなサブセット化を行うことはできません$
。ソースコード ( R/src/main/subset.c
) には、次のように記載されています。
/* $ サブセット演算子。
最初の引数のみを評価するようにする必要があります。
2 番目は、評価ではなく、一致する必要があるシンボルです。
*/
第二引数?何?!は$
、R の他のすべてのものと同様に (たとえば(
、などを含む) +
、^
引数を取り、評価される関数であることを認識する必要があります。df$V1
として書き換えることができます
`$`(df , V1)
または実際に
`$`(df , "V1")
しかし...
`$`(df , paste0("V1") )
...たとえば、2番目の引数で最初に評価する必要があるものは機能しません。評価され ない文字列のみを渡すことができます。
代わりに[
(または[[
、1 つの列のみをベクトルとして抽出する場合) を使用します。
例えば、
var <- "mpg"
#Doesn't work
mtcars$var
#These both work, but note that what they return is different
# the first is a vector, the second is a data.frame
mtcars[[var]]
mtcars[var]
do.call
への呼び出しを構築するために使用して、ループなしで順序付けを実行できますorder
。以下に再現可能な例を示します。
# set seed for reproducibility
set.seed(123)
df <- data.frame( col1 = sample(5,10,repl=T) , col2 = sample(5,10,repl=T) , col3 = sample(5,10,repl=T) )
# We want to sort by 'col3' then by 'col1'
sort_list <- c("col3","col1")
# Use 'do.call' to call order. Seccond argument in do.call is a list of arguments
# to pass to the first argument, in this case 'order'.
# Since a data.frame is really a list, we just subset the data.frame
# according to the columns we want to sort in, in that order
df[ do.call( order , df[ , match( sort_list , names(df) ) ] ) , ]
col1 col2 col3
10 3 5 1
9 3 2 2
7 3 2 3
8 5 1 3
6 1 5 4
3 3 4 4
2 4 3 4
5 5 1 4
1 2 5 5
4 5 3 5