简体   繁体   中英

Looping with A Factor in R

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.

Thanks!

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.  

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)]

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.

match=data.frame(bonegrp=c('Bone2','Bone3','Bone24','Bone5','Bone6','Bone7','Bone8','Bone9','Bone10','Bo
ne11','Bone12'),type=c('Gast 1','Gast 1','Vert1','Vert2','Femur','Tibia','Meta.','Phal','Pcau.','Mcau.','DCau'))

new_data=merge(dat,match,by='bonegrp')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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