如何从R中的重复测量中找到最终值?(How to find the final value from repeated measures in R?)

编程入门 行业动态 更新时间:2024-10-26 13:19:32
如何从R中的重复测量中找到最终值?(How to find the final value from repeated measures in R?)

我在R中安排了这样的数据:

indv time mass 1 10 7 2 5 3 1 5 1 2 4 4 2 14 14 1 15 15

indv是人口中的个体。 我想添加初始质量( mass_i )和最终质量( mass_f )的列。 我昨天了解到,我可以在plyr中使用ddply为初始质量添加一列:

sorted <- ddply(test, .(indv, time), sort) sorted2 <- ddply(sorted, .(indv), transform, mass_i = mass[1])

它给出了一个表格:

indv mass time mass_i 1 1 1 5 1 2 1 7 10 1 3 1 10 15 1 4 2 4 4 4 5 2 3 5 4 6 2 8 14 4 7 2 9 20 4

然而,这种方法不适用于找到最终质量( mass_f ),因为我对每个人的观察数量不同。 当观察的数量可能有所不同时,有人能建议找到最终质量的方法吗?

I have data arranged like this in R:

indv time mass 1 10 7 2 5 3 1 5 1 2 4 4 2 14 14 1 15 15

where indv is individual in a population. I want to add columns for initial mass (mass_i) and final mass (mass_f). I learned yesterday that I can add a column for initial mass using ddply in plyr:

sorted <- ddply(test, .(indv, time), sort) sorted2 <- ddply(sorted, .(indv), transform, mass_i = mass[1])

which gives a table like:

indv mass time mass_i 1 1 1 5 1 2 1 7 10 1 3 1 10 15 1 4 2 4 4 4 5 2 3 5 4 6 2 8 14 4 7 2 9 20 4

However, this same method will not work for finding the final mass (mass_f), as I have a different number of observations for each individual. Can anyone suggest a method for finding the final mass, when the number of observations may vary?

最满意答案

您可以简单地使用length(mass)作为最后一个元素的索引:

sorted2 <- ddply(sorted, .(indv), transform, mass_i = mass[1], mass_f = mass[length(mass)])

正如mb3041023所建议并在下面的评论中讨论的那样,您可以在不对数据框进行排序的情况下实现类似的结果:

ddply(test, .(indv), transform, mass_i = mass[which.min(time)], mass_f = mass[which.max(time)])

除行的顺序外,这与sorted2相同。

You can simply use length(mass) as the index of the last element:

sorted2 <- ddply(sorted, .(indv), transform, mass_i = mass[1], mass_f = mass[length(mass)])

As suggested by mb3041023 and discussed in the comments below, you can achieve similar results without sorting your data frame:

ddply(test, .(indv), transform, mass_i = mass[which.min(time)], mass_f = mass[which.max(time)])

Except for the order of rows, this is the same as sorted2.

更多推荐

本文发布于:2023-04-27 12:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1327124.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:测量   中找到   find   measures   repeated

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!