R paired column index

Let's say I have two matrices: A and B:

mth <- c(rep(1:5,2)) day <- c(rep(10,5),rep(11,5)) hr <- c(3,4,5,6,7,3,4,5,6,7) v <- c(3,4,5,4,3,3,4,5,4,3) A <- data.frame(cbind(mth,day,hr,v)) year <- c(2008:2012) mth <- c(1:5) B <- data.frame(cbind(year,mth)) 

I want to look like this:

 mth <- c(rep(2008:2012,2)) day <- c(rep(10,5),rep(11,5)) hr <- c(3,4,5,6,7,3,4,5,6,7) v <- c(3,4,5,4,3,3,4,5,4,3) A <- data.frame(cbind(mth,day,hr,v)) 

Basically I need to change the mth column from with the year of the column to B, Maybe I was not looking for a suitable keyword, I could not get what I want (I tried that ()), please help, thanks.

+4
source share
2 answers
 A2 <- merge(A,B, by = "mth")[ , -1] names(A2)[(which(names(A2)=="year"))] <- "mth" > A2 day hr v mth 1 10 3 3 2008 2 11 3 3 2008 3 11 4 4 2009 4 10 4 4 2009 5 11 5 5 2010 6 10 5 5 2010 7 11 6 4 2011 8 10 6 4 2011 9 10 7 3 2012 10 11 7 3 2012 
+3
source

Probably the easiest solution is to use merge , which is equivalent to joining sql in several ways:

 merge(A,B) #----- merge(A, B) mth day hr v year 1 1 10 3 3 2008 2 1 11 3 3 2008 3 2 11 4 4 2009 4 2 10 4 4 2009 5 3 11 5 5 2010 6 3 10 5 5 2010 7 4 11 6 4 2011 8 4 10 6 4 2011 9 5 10 7 3 2012 10 5 11 7 3 2012 

Perhaps you can also use match to replace mth in place:

 A$mth <- B[match(A$mth, B$mth),1] #----- mth day hr v 1 2008 10 3 3 2 2009 10 4 4 3 2010 10 5 5 4 2011 10 6 4 5 2012 10 7 3 6 2008 11 3 3 7 2009 11 4 4 8 2010 11 5 5 9 2011 11 6 4 10 2012 11 7 3 

While a bit tight, this code indexes B by matching the two columns mth from A and B , and then captures the first column. +

+3
source

Source: https://habr.com/ru/post/1439719/


All Articles