Merge and sum two data frames doesn't work as expected in R

16 views Asked by At

I have two data frames with presence data (camTraps and Tunnels), using each a different detection method. I want to merge and sum these two data frames in order to have a unique data frame returning all presences confounded.

However, the code I am using returns something odd : both data frames have 105 observations, yet the output data frame has only 9 observations !

Here is a brief overview of my data frames, which have 105 rows and 22 columns :

Sites Species week1 week2 etc.
M1 M.erminea 1 0 etc.
F1 M. martes 0 0 etc.
etc. etc. etc. etc. etc.

And this is the code I0m currently using :

camTraps <- as.data.frame(camTraps)
Tunnels <- as.data.frame(Tunnels)

#merge the two data frames
TotOcup <-rbind(camTraps[, 3:22],Tunnels[, 3:22])
TotOcup <- do.call(rbind, lapply(split(TotOcup, sapply(rownames(TotOcup),substr,1,1)), colSums))
#there cannot be 9 obs. when there is 105 obs. in each dataset !
TotOcup <- as.data.frame(TotOcup)
TotOcup[1:20] <- lapply(TotOcup[1:20], function(x) ifelse(x >= 1, 1, 0))
TotOcup <- cbind(camTraps[, c(1, 2)], TotOcup) #doesn't work since 105 vs. 9 obs.

Indeed, I expected an output data frame with 105 rows and 22 columns.

0

There are 0 answers