Return 数据框只有最后一次观察,例如患者,使用 Rcpp

Return dataframe with only last observations of e.g. patients, using Rcpp

我有一个数据框,每个人有多行,这些对应于不同的考试日期。我现在想使用 Rcpp 编写一个函数,以便我得到一个只包含最后一次观察的数据框。我目前在 R 中有一个代码(根据 http://www.ats.ucla.edu/stat/r/faq/firstlast.htm 调整),但是由于数据框有超过 20000 行和 200 个变量,所以速度太慢了。

# function
 last.obs <- function(id,data){
   args <- as.list(match.call())[-1]
   tmp <- data
   tmp$id <- eval(args$id,data)
   uni.id <- unique(tmp$id)

   last <- c()

   for (i in unique(uni.id)){
    temp<-tmp[which(tmp$id==i),]
    if (dim(temp)[1] > 1){
     last.temp<-temp[dim(temp)[1],]
    }else{last.temp<-temp}
    last<-rbind(last, last.temp)
   }
   last
  }

# create sample data
data <- data.frame("id"=sort(sample(letters[1:3],20,T)),"x1"=rnorm(20),
"x2"=rnorm(20), "x3"=sample(c("Drug","Treatment"),20,T))

# example of function
last.obs(id,data)

我试过用 C++ 写这个,但我对写整个函数的了解还不够。我在对数据进行子集化时遇到了麻烦,只保留最后一行并找到 rbind 的 C++ 等价物。我真的很想在 C++ 方面做得更好,所以如果有人能帮助我,我真的很感激。这是我到目前为止的代码(对不起,糟糕的代码)。

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export("lastobs")]]
Rcpp::DataFrame lastobs(Rcpp::CharacterVector id, Rcpp::DataFrame data){
int unid = id.size();
Rcpp::CharacterVector id_data = data["id"];
Rcpp::CharacterVector id_loop;
Rcpp::NumericVector matchid;
Rcpp::DataFrame lastobs;

for(int i=0; i<unid;i++){
 id_loop = id(i);
 matchid = Rcpp::match(id_data,id_loop); 
// I do not know I can best proceed from here
}
return lastobs;
}
> df = data.frame(A = c(1,2,2,3,3,3), B = c('a','a','b','a','b','c'))

  A B
1 1 a
2 2 a
3 2 b
4 3 a
5 3 b
6 3 c

第一次观察:

> df[!duplicated(df$A), ]
  A B
1 1 a
2 2 a
4 3 a

最后一次观察:

> df[rev(!duplicated(rev(df$A))), ]

  A B
1 1 a
3 2 b
6 3 c