0

I would like to fill a dataframe ("DF") with 0's or 1's depending if values in a vector ("Date") match with other date values in a second dataframe ("df$Date"). If they match the output value have to be 1, otherwise 0.

I tried to adjust this code made by a friend of mine, but it doesn't work:

for(j in 1:length(Date)) {  #Date is a vector with all dates from 1967 to 2006
    # Start count
    count <- 0
    # Check all Dates between 1967-2006
    if(any(Date[j] == df$Date)) { #df$Date contains specific dates of interest
      count <- count + 1
    }
    # If there is a match between Date and df$Date, its output is 1, else 0.
    DF[j,i] <- count
  }

The main dataframe "DF" has got 190 columns, which have to filled, and of course a number of rows equal to the Date vector.


extra info


1) Each column is different from the other ones and therefore the observations in a row cannot be all equal (i.e. in a single row, I should have a mixture between 0's and 1's). 2) The column names in "DF" are also present in "df" as df$Code.

1 Answers1

0

We can vectorize this operation with %in% and as.integer(), leveraging the fact that coercing logical to integer returns 0 for false and 1 for true:

Mat[,i] <- as.integer(Date%in%df$Date);

If you want to fill every single column of Mat with the exact same result vector:

Mat[] <- as.integer(Date%in%df$Date);

My above code exactly reproduces the logic of the code in your (original) question.

From your edit, I'm not 100% sure I understand the requirement, but my best guess is this:

set.seed(4L);
LV <- 10L; ND <- 10L;
Date <- sample(seq_len(ND),LV,T);
df <- data.frame(Date=sample(seq_len(ND),3L),Code=c('V1','V2','V3'));
DF <- data.frame(V1=rep(NA,NV),V2=rep(NA,NV),V3=rep(NA,NV));
Date;
##  [1]  6  1  3  3  9  3  8 10 10  1
df;
##   Date Code
## 1    8   V1
## 2    3   V2
## 3    1   V3
for (cn in colnames(DF)) DF[,cn] <- as.integer(Date%in%df$Date[df$Code==cn]);
DF;
##    V1 V2 V3
## 1   0  0  0
## 2   0  0  1
## 3   0  1  0
## 4   0  1  0
## 5   0  0  0
## 6   0  1  0
## 7   1  0  0
## 8   0  0  0
## 9   0  0  0
## 10  0  0  1
bgoldst
  • 34,190
  • 6
  • 38
  • 64
  • hi, thanks a lot for your help. your code works perfectly but I think I expressed not so well my question (it is not easy). You can see the update. –  Jul 07 '16 at 17:36
  • great. Thanks a lot. –  Jul 07 '16 at 19:56