简体   繁体   中英

filter data frame based on new data frame

Here is some toy data

x <- c("Bird","Bird","Tiger","Bird","Fish","grey","blue","orange","green","yellow","10","5","7","12","5","10","10","8","12","2","10","20","10","18","3")
m <- matrix(x,byrow = F,ncol = 5,nrow= 5)
m <- as.data.frame(m)
colnames(m) <- c("Animal","colour","length","height","weight")

y <- c("Tiger","Bird","Bird","colour","length","colour","orange","10","green","orange/black","12","light green")
new.m <- matrix(y,byrow=F,ncol=4,nrow = 3)
new.m <- as.data.frame(new.m)
colnames(new.m) <- c("Animal","attribute","value","new value")

How can I efficiently update the values in m using the data frame new.m . The final result should look like this:

z <- c("Bird","Bird","Tiger","Bird","Fish","grey","blue","orange/black"," light green","yellow","12","5","7","12","5","10","10","8","12","2","10","20","10","18","3")
update.m <- matrix(z,byrow = F,ncol = 5,nrow= 5)
update.m <- as.data.frame(update.m)
colnames(update.m) <- c("Animal","colour","length","height","weight")

For a fixed row in new.m I can achieve this easily. But can this be done in comprehensive not row based way?

One idea via base R. We first create a matrix with the columns we need to update the values. We use match to update the values. The nomath entries result to NA which we replace with original values and put them back in the original data frame.

m3 <- sapply(m[c(2:3)], function(i) new.m$`new value`[match(i, new.m$value)])
m[c(2:3)] <- replace(m3, is.na(m3), m[c(2,3)][which(is.na(m3), arr.ind = TRUE)])

m
#  Animal       colour length height weight
#1   Bird         grey     12     10     10
#2   Bird         blue      5     10     20
#3  Tiger orange/black      7      8     10
#4   Bird  light green     12     12     18
#5   Fish       yellow      5      2      3

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