2016-09-24 3 views
2

私はいくつかの条件のリストを持っており、それらの組み合わせを評価したいと思います。そして、これらの論理値のバイナリ値を取得したいと思います(True = False = 0)。私のプロジェクトが進行するにつれて、条件自体が変わるかもしれないし、成長していくかもしれないので、スクリプトの中の1つの場所で、これらの条件文を変更することができます。ここで ステートメントのベクトルから論理値のデータフレームを取得する

は単純化され、再現性の例である:

# get the data 
df <- data.frame(id = c(1,2,3,4,5), x = c(11,4,8,9,12), y = c(0.5,0.9,0.11,0.6, 0.5)) 

# name and define the conditions 
names1 <- c("above2","above5") 
conditions1 <- c("df$x > 2", "df$x >5") 

names2 <- c("belowpt6", "belowpt4") 
conditions2 <- c("df$y < 0.6", "df$y < 0.4") 

# create an object that contains the unique combinations of these conditions and their names, to be used for labeling columns later 

names_combinations <- as.vector(t(outer(names1, names2, paste, sep="_"))) 

condition_combinations <- as.vector(t(outer(conditions1, conditions2, paste, sep=" & "))) 

# create a dataframe of the logical values of these conditions 

condition_combinations_logical <- ????? # This is where I need help 

# lapply to get binary values from these logical vectors 

df[paste0("var_",names_combinations] <- +(condition_combinations_logical) 

のようなものを見ることができる出力を得るために:

-id -- | -x -- | -y -- | -var_above2_belowpt6 -- | -var_above2_belowpt4 -- | etc. 
1  | 11 | 0.5 | 1      | 0      | 
2  | 4 | 0.9 | 0      | 0      | 
3  | 8 | 0.11 | 1      | 1      | 
etc. .... 

答えて

1

は、それが(ハードがはるかに簡単に考えるためにない恐ろしいeval(parse())のように見えます方法...)。次にstorage.mode()<-を使用して論理から整数に変換してください。

res <- sapply(condition_combinations,function(x) eval(parse(text=x))) 
storage.mode(res) <- "integer" 
+0

ここではeval(parse())を使用するのに間違いはないと思います。これが意図されていることです。 – dracodoc

関連する問題