使用另一列

时间:2018-06-11 23:09:06

标签: r conditional data-manipulation

我正在尝试创建一个新变量,其中值被指定为另一列中特定顺序值集的函数。 下面举例说明10项测试的状态(正面或负面):

    df<-data.frame(Trank=c(1:10), status=c(0,1,0,0,1,1,0,1,0,1))

现在,新列“class”中的值应按照以下规则分配:class =“a”如果当前测试为负但前两个测试为正,class ==“b”如果目前的测试是积极的,但前一个测试是否定的,否则为class ==“c”。在这个例子中,我会得到类似的东西:

Trank status class
  1      0     c
  2      1     b
  3      0     c
  4      0     c
  5      1     b
  6      1     c
  7      0     a
  8      1     b
  9      0     c
 10      1     b

我无法弄清楚获取此输出的条件函数应该如何。 我为没有发布任何尝试而道歉,但我真的很不满。任何建议/建议都会非常感激!非常感谢!

1 个答案:

答案 0 :(得分:1)

我们可以#include <iostream> #include <vector> #include <algorithm> #include <tuple> typedef std::vector<std::vector < int>> Type ; struct Chrom // to demonstrate { Type bit; }; std::tuple<int, int, int> findPosition(const std::vector<Chrom>& vec3D, const int& val) { int First = 0, Second = 0, Third = -1; // initilize the positions for(const Chrom& each_chrom: vec3D) { for(const std::vector<int>& innerVec: each_chrom.bit) { std::vector <int>::const_iterator get_pos; get_pos = std::find(innerVec.cbegin(), innerVec.cend(), val); Third = (*get_pos == val) ? get_pos - innerVec.cbegin(): -1; // check val found otherwise -1 if(Third != -1) return std::make_tuple(First, Second, Third); // if found return them ++Second; } Second = 0; Third = -1; ++First; } return std::make_tuple(First, Second, Third); } int main() { // this is a 3 dimensional vector std::vector<Chrom> popcurrent(2); // position inside the popcurrent popcurrent[0].bit = { {3,2,1}, // (0,0,0) (0,0,1) (0,0,2) {3,10,1} }; // (0,1,0) (0,1,1) (0,1,2) popcurrent[1].bit = { {5,8,11}, // (1,0,0) (1,0,1) (1,0,2) {4,7,1} }; // (1,1,0) (1,1,1) (1,1,2) int pos_popcurrent, pos_bit, pos_inner_vec; for(int val = 1; val <= 12; ++val) { std::cout << "\nCurrently looking for: " << val ; std::tie(pos_popcurrent, pos_bit, pos_inner_vec) = findPosition(popcurrent, val); (pos_inner_vec != -1) ? std::cout << " found @ popcurrent[ " << pos_popcurrent << " ].bit[ " << pos_bit << " ][ " << pos_inner_vec <<" ]": std::cout << " Not found"; } return 0; } 使用Currently looking for: 1 found @ popcurrent[ 0 ].bit[ 0 ][ 2 ] Currently looking for: 2 found @ popcurrent[ 0 ].bit[ 0 ][ 1 ] Currently looking for: 3 found @ popcurrent[ 0 ].bit[ 0 ][ 0 ] Currently looking for: 4 found @ popcurrent[ 1 ].bit[ 1 ][ 0 ] Currently looking for: 5 found @ popcurrent[ 1 ].bit[ 0 ][ 0 ] Currently looking for: 6 Not found Currently looking for: 7 found @ popcurrent[ 1 ].bit[ 1 ][ 1 ] Currently looking for: 8 found @ popcurrent[ 1 ].bit[ 0 ][ 1 ] Currently looking for: 9 Not found Currently looking for: 10 found @ popcurrent[ 0 ].bit[ 1 ][ 1 ] Currently looking for: 11 found @ popcurrent[ 1 ].bit[ 0 ][ 2 ] Currently looking for: 12 Not found 来编码不同的条件

dplyr::lag