Fill data frame rows with new values

I want to set an empty data frame with existing data (according to the names of one column). Say my empty data:

#define empty data.frame predictor.names <- c("LO3","Tx","Gh","RH","SR","ST","TC","U10","WF","SF","F","VW","VS","V","D","day") dat <- data.frame("pred"=predictor.names,"MAM"=0) rownames(dat) <- predictor.names 

Now I want to fill the lines with the following values:

  x Freq SR 392 RH 350 day 253 Tx 90 LO3 28 ST 7 TC 5 WF 5 VS 2 SF 1 

then I tried:

  dat[which(dat$pred%in%temp[[1]]),2] <- temp[[2]] 

But this does not work, because the order of the variables is different. he adds 392 to the first LO3 and so on. so I'm going to do it with a loop ... but there should be another easier way. Any idea / suggestion?

Thanks in advance!

+5
source share
1 answer

You can try using match to get a numerical index and use it to assign values.

  indx <- match(temp$x, dat$pred) dat$MAM[indx] <- temp$Freq 

data

  temp <- structure(list(x = c("SR", "RH", "day", "Tx", "LO3", "ST", "TC", "WF", "VS", "SF"), Freq = c(392L, 350L, 253L, 90L, 28L, 7L, 5L, 5L, 2L, 1L)), .Names = c("x", "Freq"), class = "data.frame", row.names = c(NA, -10L)) 
+3
source

All Articles