在第一个实例中按行拆分数据

时间:2018-04-27 09:00:04

标签: r dataframe

我试图在某个值的第一个实例中按行将数据帧拆分为两个,即不按组拆分。例如,如果我的数据是:

patid disease
3     Z
99    B
4     A
1002  B
43    A
745   C
399   Z
545   A 
8     A

我想要两个数据帧,第一个数据帧包含前两个ptid行,第二个包含所有其他数据帧,即我从疾病A的第一个实例中分离出来。最终我将丢弃所有来的在A之前,即疾病B和Z的前两次出现。

请注意,我不能以任何方式订购行,因为这些是时间过程(病历)记录。

我可以在循环中轻松完成!但是,我知道R不支持循环。

3 个答案:

答案 0 :(得分:3)

如果您的最终目标是对数据进行分组,则可以直接执行此操作:

subset(df, cumsum(disease == "A") >= 1)
#  patid disease
#3     4       A
#4  1002       B
#5    43       A
#6   745       C
#7   399       Z
#8   545       A
#9     8       A

但是如果你想分割数据,你可以这样做:

split(df, cumsum(df$disease == "A") >= 1)
# $`FALSE`
# patid disease
# 1     3       Z
# 2    99       B
# 
# $`TRUE`
# patid disease
# 3     4       A
# 4  1002       B
# 5    43       A
# 6   745       C
# 7   399       Z
# 8   545       A
# 9     8       A

答案 1 :(得分:3)

另一种方法是使用which.max获取disease列中第一次出现“A”的索引,然后获取所有行。

df[which.max(df$disease == "A"):nrow(df), ]

#  patid disease
#3     4       A
#4  1002       B
#5    43       A
#6   745       C
#7   399       Z
#8   545       A
#9     8       A

使用match

也可以实现同样的目的
df[match("A", df$disease):nrow(df), ]

答案 2 :(得分:2)

你可以完全使用which.min和grepl函数:

  patid disease
3     4       A
4  1002       B
5    43       A
6   745       C
7   399       Z
8   545       A
9     8       A

获得

function palTest(string) {
  var lastIndex = string.length - 1; //initialize lastIndex here
  let j = string[lastIndex];
  if (string.length % 2 === 0) {
    for (i = 0; i <= string.length / 2; i++) {
      if (string[i] === string[lastIndex]) { //compare with lastIndex
        lastIndex--; //decrement last index
        return true;
      } else {
        return false;
      }
    }
  } else {
    let middleCharacter = (string.length + 1) / 2;
    for (i = 0; i <= ((string.length + 1) / 2) - 1; i++) {
      if (string[i] === string[lastIndex] && middleCharacter == "a" || "e" || "i" || "o" || "u") {
        lastIndex--;
        return true;
      } else {
        return false;
      }
    }
  }
}

console.log( palTest("hannah") );
console.log( palTest("hantnah") );
console.log( palTest("Not a palindrome") );