Reputation: 59
I have two datasets animal and plants
ANIMAL PLANT
OBS Common Animal Number OBS Common Plant Number
1 a Ant 5 1 g Grape 69
2 b Bird 2 h Hazelnut 55
3 c Cat 17 3 i Indigo
4 d Dog 9 4 j Jicama 14
5 e Eagle 5 k Kale 5
6 f Frog 76 6 l Lentil 77
I want to concatenate these two into a new dataset.
Below is the desired output
Obs Common Animal Plant Number
1 a Ant 5
2 b Bird .
3 c Cat 17
4 d Dog 9
5 e Eagle .
6 f Frog 76
7 g Grape 69
8 h Hazelnut 55
9 i Indigo .
10 j Jicama 14
11 k Kale 5
12 l Lentil 77
How to do these kind of concatenate in R?
Upvotes: 0
Views: 433
Reputation: 153
This should give you the desired output:
PLANT$OBS = PLANT$OBS + nrow(ANIMAL)
ANIMAL$Plant = ''
PLANT$Animal = ''
Final_DF= rbind(ANIMAL,PLANT)
Upvotes: 0
Reputation: 3488
rbind()
will not work because of the differing names.
Something like this will work for the given example:
rbind_ <- funciton(data1, data2) {
nms1 <- names(data1)
nms2 <- names(data2)
if(mean(nms1==nms2)==1) {
out <- rbind(data1, data2)
} else {
data1[nms2[!nms2%in%nms1]] <- NA
data2[nms1[!nms1%in%nms2]] <- NA
out <- rbind(data1, data2)
}
return(out)
}
rbind_(animal, plant)
OBS Common Animal Number Plant
1 1 a Ant 5 <NA>
2 2 b Bird NA <NA>
3 3 c Cat 17 <NA>
4 4 d Dog 9 <NA>
5 5 e Eagle NA <NA>
6 6 f Frog 76 <NA>
7 1 g <NA> 69 Grape
8 2 h <NA> 55 Hazelnut
9 3 i <NA> NA Indigo
10 4 j <NA> 14 Jicama
11 5 k <NA> 5 Kale
12 6 l <NA> 77 Lentil
But would require a bit of tweaking to get to work in all cases, I think.
Upvotes: 1