Search code examples
rrowsmelt

Uniting several rows of data frame


Is there a way to unite several rows of a data frame with multiple columns?

I have data from different animal organs - I want to contrast individuals' organs. One row should contain only measurements of an individual but from all sampled organs (columns). Any idea? I tried the melt command did not manage it.

Here is some of my data:

structure(list(ID = c("BB1", "BB1", "BB1"), ID.organ = c("BB1-B", 
"BB1-L", "BB1-M"), d15NAIR = c(6.244803447, 5.263374719, 6.28820367
), brain = c(-31.00047084, NA, NA), eyes = c(NA_real_, NA_real_, 
NA_real_), liver = c(NA, -30.8483728, NA), muscle = c(NA, NA, 
-29.67755736)), row.names = c(NA, 3L), class = "data.frame")

Solution

  • I found the solution although it seems bit stupid, because the mean is not computing acutal arithmetic means:

    my_data <- my_data[,-c(2,3)] %>%
      pivot_longer(cols = brain:muscle) 
        
    acast(my_data, ID ~ name, mean,na.rm=T)
    

    Then it takes the original value.