从语句向量中获取逻辑值的数据帧

时间:2016-09-24 23:20:29

标签: r logical-operators

我有很多条件列表,我想评估它们的组合,然后我想获得这些逻辑值的二进制值(True = 1,False = 0)。随着项目的进展,条件本身可能会发生变化或增长,因此我希望脚本中有一个位置可以更改这些条件语句,而脚本的其余部分保持不变。

这是一个简化的,可重现的例子:

# 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 个答案:

答案 0 :(得分:1)

看起来可怕的php example.php > temp.txt 做到了(很难想到更简单的方法......)。然后使用eval(parse())将逻辑转换为整数...

storage.mode()<-