用于在向量中查找第一个和最后一个变量的函数 [英] Functions for finding first and last variables in the vector

查看:32
本文介绍了用于在向量中查找第一个和最后一个变量的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个 R 函数来查找向量中的第一个和最后一个变量,类似于 min 的最小值和 max 的最大值.我知道我可以计算向量的长度,然后从那里开始,但它不能满足我的需要.

I am looking for an R function to find first and last variables in the vector similar to min for minimal and max for maximal. I know I can calculate the length of the vector, and go from there but it does not work for what I need it for.

我有以下数据集(实际上要大得多):

I have a following dataset (in reality much larger):

a<-(c("2013-02-25","2013-03-13","2013-04-24","2013-05-12","2013-07-12","2013-08-11","actual_exam_date"))
b<-c(300,230,400,NA,NA,NA,"2013-04-30")
c<-c(NA,260,410,420,NA,NA,"2013-05-30")
d<-c(300,230,400,NA,370,390,"2013-08-30")
df<-as.data.frame(rbind(b,c,d))
colnames(df)<-a
rownames(df)<-(c("student 1","student 2","student 3"))
df$student_id <- row.names(df)
library('reshape2')
df2 <- melt(df, id.vars = c('student_id','actual_exam_date'),
                variable.name = 'pretest_date',
                value.name = 'pretest_score')
df2 <- df2[!is.na(df2$pretest_score),]
df2$actual_exam_date <- as.Date(df2$actual_exam_date)
df2$pretest_date <- as.Date(df2$pretest_date)
df2$days_before_exam <- as.integer(df2$actual_exam_date - df2$pretest_date)
df2$pretest_score <- as.numeric(df2$pretest_score)
df2

我计算每个学生最高分数的方法是这样的:

The way I was able to calculate the maximum scores for each student was this:

aggregate(pretest_score ~ student_id, df2, max)

现在我想确定每个学生的第一个和最后一个预测试分数,以计算它们之间的差异.有没有办法使用聚合来做到这一点?

Now I am looking to identify the first and last pretest scores for each student, to calculate the difference between them. Is there a way to do it using aggregate?

推荐答案

使用 data.table 的另一个建议,它允许您在不指定匿名函数的情况下订购(如果需要)并获得结果单行

Just another suggestion using data.table which allows you both order (if needed) and get the result without specifying anonymous functions and in a single line

library(data.table)
setDT(df2)[order(pretest_date), diff(pretest_score[c(1, .N)]), keyby = student_id]
#    student_id  V1
# 1:  student 1 100
# 2:  student 2 160
# 3:  student 3  90

这篇关于用于在向量中查找第一个和最后一个变量的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆