R中的一个因数循环 [英] Looping with A Factor in R

查看:91
本文介绍了R中的一个因数循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,此代码根据因子bonegrp的值填充向量Bone的值.我想以更简洁的方式完成此操作.

So this code fills in the values of the vector Bone according to the value of the factor bonegrp. I would like to accomplish this in a more concise manner.

谢谢!

v <- dat$bonegrp=="Bone2"  
Bone[v] <- "Gast 1"  
v <- dat$Bonegrp=="Bone3"  
Bone[v] <- "Gast 2"  
v <- dat$Bonegrp=="Bone4"  
Bone[v] <- "Vert1"  
v <- dat$Bonegrp=="Bone5"  
Bone[v] <- "Vert2"  
v <- dat$Bonegrp=="Bone6"  
Bone[v] <- "Femur"  
v <- dat$Bonegrp=="Bone7"  
Bone[v] <- "Tibia"  
v <- dat$Bonegrp=="Bone8"   
Bone[v] <- "Meta."  
v <- dat$Bonegrp=="Bone9"  
Bone[v] <- "Phal."  
v <- dat$Bonegrp=="Bone10"  
Bone[v] <- "PCau."  
v <- dat$Bonegrp=="Bone11"  
Bone[v] <- "MCau."  
v <- dat$Bonegrp=="Bone12"  
Bone[v] <- "DCau.  

推荐答案

如果Bonegrp中只有12个级别,那么您可以查看是否可行(根据有关数据结构的其他信息进行编辑):

If there are only 12 levels in Bonegrp then you could see if this works (edited per additional info regarding data structure):

Bone <- c(NA, "Gast 1", "Gast 2", "Vert1", "Vert2", "Femur","Tibia", "Meta.", 
          "Phal.", "PCau.", "MCau.", "DCau.")[as.numeric(dat$Bonegrp)]

它基本上是使用向量,并根据Bonegrp的数值等效项查找适当的字符串.您真的应该提供有关数据的更多信息.仅仅提供代码通常是不够的.

It is basically using a vector and looking up the proper string based on the numeric equivalent of Bonegrp. You really should provide more information about your data. Just provided code is often not enough.

这篇关于R中的一个因数循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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