2017-05-12 7 views
0

フィルタされた列に基づいて関数内のデータフレーム列を更新しようとしています。列の引数を持つ関数内のデータフレームのフィルタ

#example dataframe 
my.df = data.frame(A=1:10) 

#define function to classify column passed as argument 2 based on argument 3 
classify = function(df, col, threshold){ 
    df[df$col<threshold, 2] <- "low" 
    df[df$col>=threshold, 2] <- "high" 

    return(df) 
} 

#assign output to new.df 
new.df = classify(my.df, A, 5) 

私は「低」または「高」の文字値を格納するための新しい列を期待するが、代わりに、彼らはすべての<NA>です。

+0

のmutate(my.df、Bは= ifelse(A <2) '高'、 '低')? –

答えて

0

は単に列名、"A"のリテラル文字列を渡し、その後、関数内受け取るunquotingによってmutate/group_by/filter等内で評価されるquosureに変換します$有するシングルまたはダブルブラケット[[...]]インデックスとしないでパラメータ:

# example dataframe 
my.df = data.frame(A=1:10) 

# define function to classify column passed as argument 2 based on argument 3 
classify = function(df, col, threshold){ 
    df[df[[col]] < threshold, 2] <- "low" 
    df[df[[col]] >= threshold, 2] <- "high" 

    return(df) 
} 

# assign output to new.df 
new.df = classify(my.df, "A", 5) 

new.df  
#  A V2 
# 1 1 low 
# 2 2 low 
# 3 3 low 
# 4 4 low 
# 5 5 high 
# 6 6 high 
# 7 7 high 
# 8 8 high 
# 9 9 high 
# 10 10 high 
0

これを行うには、dplyr(すぐにリリースされる予定です)を使用することができます。 enquoは、入力引数を取り、(UQ

library(dplyr) 
classify <- function(df, col, threshold){ 
    col <- enquo(col) 

    df %>% 
     mutate(categ = ifelse(UQ(col) < threshold, "low", "high")) 

} 

classify(my.df, A, 5) 
# A categ 
#1 1 low 
#2 2 low 
#3 3 low 
#4 4 low 
#5 5 high 
#6 6 high 
#7 7 high 
#8 8 high 
#9 9 high 
#10 10 high 
関連する問題