0

I am very very new to R. My problem is that I have a database where I want to select 3 columns:

Flower color Insect Species who visit the flower Number of insects
White A. mellifera 3
White B. terrestris 1
Yellow X. violacea 2
Yellow A. mellifera 5
Purple X. violacea 10

I want to test if these species have a preference for flowers. So I want to build a table which looks like that:

Flower color A. mellifera B. terrestris X. violacea
White 3 1 0
Yellow 5 0 2
Purple 0 0 10

But I don't know how, I tried using "fill" argument in table() function, but it displays 1 table for each "number of insects" data that I have.

Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
Raúl
  • 3
  • 2

1 Answers1

0

We can use xtabs

> xtabs(NumberOfInsects~.,df)
           InsectSpecieswhoVisitTheFlower
Flowercolor A.mellifera B.terrestris X.violacea
     Purple           0            0         10
     White            3            1          0
     Yellow           5            0          2

or reshape

reshape(
  df,
  direction = "wide",
  idvar = "Flowercolor",
  timevar = "InsectSpecieswhoVisitTheFlower"
)

which gives

  Flowercolor NumberOfInsects.A.mellifera NumberOfInsects.B.terrestris
1       White                           3                            1
3      Yellow                           5                           NA
5      Purple                          NA                           NA
  NumberOfInsects.X.violacea
1                         NA
3                          2
5                         10

Data

> dput(df)
structure(list(Flowercolor = c("White", "White", "Yellow", "Yellow", 
"Purple"), InsectSpecieswhoVisitTheFlower = c("A.mellifera",
"B.terrestris", "X.violacea", "A.mellifera", "X.violacea"), NumberOfInsects = c(3L,
1L, 2L, 5L, 10L)), class = "data.frame", row.names = c(NA, -5L
))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81