简体   繁体   English

从给定的水平因子获得下一个水平

[英]Get next level from a given level factor

I am currently making my first steps using R with RStudio and right now I am struggling with the following problem: I got some test data about a marathon with four columns, where the third column is a factor with 15 levels representing different age classes.我目前正在使用 R 和 RStudio 迈出第一步,现在我正在努力解决以下问题:我得到了一些关于四列马拉松的测试数据,其中第三列是代表不同年龄段的 15 个级别的因子。 One age class randomAgeClass will be randomly selected at the beginning, and an object is created holding the data that matches this age class.一开始将随机选择一个年龄 class randomAgeClass ,并创建一个 object 来保存与该年龄 class 匹配的数据。

set.seed(12345678)
attach(marathon)
randomAgeClass <- sample(levels(marathon[,3]), 1)
filteredMara <- subset(marathon, AgeClass == randomAgeClass)

My goal is to store a second object that holds the data matching the next higher level, meaning that if age class 'kids' was randomly selected, I now want to access the data relating to 'teenagers', which is the next higher level.我的目标是存储第二个 object 来保存与下一个更高级别匹配的数据,这意味着如果随机选择年龄 class 'kids',我现在想访问与下一个更高级别的 'teenagers' 相关的数据。 Looking something like this:看起来像这样:

nextAgeClass <- .... randomAgeClass+1 .... ?
filteredMaraAgeClass <- subset(marathon, AgeClass == nextAgeClass)

Note that I already found this StackOverflow question, which seems to partially match my situation, but the accepted answer is not understandable to me, thus I wasn't able to apply it to my needs.请注意,我已经找到了这个StackOverflow 问题,它似乎部分符合我的情况,但接受的答案对我来说是无法理解的,因此我无法将其应用于我的需要。

Thanks a lot for any patient help!非常感谢任何耐心的帮助!

First you have to make sure thar the levels of your factor are ordered by age:首先,您必须确保因子的水平按年龄排序:

factor(marathon$AgeClass,levels=c("kids","teenagers",etc.))

Then you almost got there in your example:然后你几乎在你的例子中到达了那里:

next_pos<-which(levels(marathon$AgeClass)==randomAgeClass)+1 #here you get the desired position in the level vector
nextAgeClass <- levels(marathon$AgeClass) [next_pos]
filteredMaraAgeClass <- subset(marathon, AgeClass == nextAgeClass)

You might have a problem if the randomAgeClass is the last one, so make sure to avoid that problem如果randomAgeClass是最后一个,您可能会遇到问题,因此请确保避免该问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM