Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fill data frame rows with new values

Tags:

r

I want to fit an empty data frame with pre-existing data (according to the names of one column). Let's say my empty data is:

        #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 rows 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 it does not work, because the order of the variables is different.. it adds 392 to first LO3 and so on.. so I am thinking to do this with a loop..but there must be another easier way.. Any idea/suggestion?

Thanks in advance!

like image 981
user3231352 Avatar asked Oct 19 '22 13:10

user3231352


1 Answers

You can try with match to get the numeric index and use that for assigning the 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))
like image 177
akrun Avatar answered Oct 23 '22 08:10

akrun