1

I am very new to working in r, and i hope to get some help with writing code.

Below is the summary data frame, BARCODE is the name each sample treatment, in each sample treatment, there are datasets for either 'pos' or 'neg', which stands for positive and negative controls.

How do i write some code to calculate CV% for variables in EXPERIMENT_TYPE in each BARCODE? CV% can be calculated by the formula below, mean_pos/sd_pos*100%

BARCODE EXPERIMENT_TYPE     MEAN         SD
1 ACC_MCF10A            neg 1882.700  421.39194
2 ACC_MCF10A            pos  158.500   60.80328
3 ACC_Rad21             neg 2219.714 1069.38612
4 ACC_Rad21             pos  134.950   81.46131

What i want in the data output is something like this

BARCODE      CV%_pos    CV%_neg
1 ACC_MCF10A   
2 ACC_Rad21 

Thank you! Any helps would be appreciated!!!!

Hannah1212
  • 11
  • 2
  • Based on your example data can you show the expected output, i.e. fill the empty cells for `CV%_pos` and `CV%_neg`? – markus Aug 09 '18 at 09:12
  • Hi there, the expected output for CV%pos or CV%neg would be the product from calculating sd/mean*100 for each pos and neg. does it make sense? thank you! – Hannah1212 Aug 09 '18 at 09:19

1 Answers1

1

Here is a tidyverse option

library(tidyverse)
df %>% 
  group_by(BARCODE, EXPERIMENT_TYPE) %>% 
  summarise(CV = SD / MEAN*100) %>%
  rename(EXPERIMENT_TYPE = CV,
         `CV%` = EXPERIMENT_TYPE) %>% # here we (more or less) swap column names
  spread(`CV%`, EXPERIMENT_TYPE, sep = "_")
# A tibble: 2 x 3
# Groups:   BARCODE [2]
#   BARCODE    `CV%_neg` `CV%_pos`
#   <chr>          <dbl>     <dbl>
# 1 ACC_MCF10A      22.4      38.4
# 2 ACC_Rad21       48.2      60.4

data

df <- structure(list(BARCODE = c("ACC_MCF10A", "ACC_MCF10A", "ACC_Rad21", 
"ACC_Rad21"), EXPERIMENT_TYPE = c("neg", "pos", "neg", "pos"), 
    MEAN = c(1882.7, 158.5, 2219.714, 134.95), SD = c(421.39194, 
    60.80328, 1069.38612, 81.46131)), .Names = c("BARCODE", "EXPERIMENT_TYPE", 
"MEAN", "SD"), class = "data.frame", row.names = c("1", "2", 
"3", "4"))
markus
  • 25,843
  • 5
  • 39
  • 58