4

I am an absolute beginner and really struggling - can anyone please help and tell me why I get that error message and how to resolve it?

This is what I am trying to do: enter image description here

and this is my data:

Location,S1,S2,S3,S4,C1,C2,TS3
PC_recapped,7.31,7.46,12.17,10.77,6.59,15.94,14.97
PC_infested,3.20,2.63,11.30,5.72,0.00,0.00,16.77
PC_recapped_and_infested,85.71,83.33,30.77,82.35,0.00,0.00,25.00
PC_normal_mites,85.71,100.00,69.23,76.47,0.00,0.00,39.29
Artem
  • 3,304
  • 3
  • 18
  • 41
Natasha Reece
  • 53
  • 1
  • 5
  • 1
    You're using `%>%` wrongly. You're already piping file name to `read_csv`, don't specify it second time as it's used as a second argument `col_names`. Please read about [usage of pipes](https://github.com/tidyverse/magrittr/blob/master/README.Rmd#usage). – pogibas Sep 30 '18 at 10:21
  • 1
    Welcome to Stack Overflow! Please read the info about [how to ask a good question](https://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – Paul Oct 01 '18 at 02:45

1 Answers1

6

To use thefct_relevel function of the forcats package to change level in a factor column, you need to transform wide formate data.frame into the narrow format using e.g. melt function of reshape2 package.

Please see the code below:

df <- structure(list(Location = structure(c(3L, 1L, 4L, 2L), .Label = c("PC_infested", 
"PC_normal_mites", "PC_recapped", "PC_recapped_and_infested"), class = "factor"), 
    S1 = c(7.31, 3.2, 85.71, 85.71), S2 = c(7.46, 2.63, 83.33, 
    100), S3 = c(12.17, 11.3, 30.77, 69.23), S4 = c(10.77, 5.72, 
    82.35, 76.47), C1 = c(6.59, 0, 0, 0), C2 = c(15.94, 0, 0, 
    0), TS3 = c(14.97, 16.77, 25, 39.29)), class = "data.frame", row.names = c(NA, 
-4L))

library(reshape2)
library(forcats)

res <- df %>% melt(id = "Location") %>% rename(c("variable" = "type")) %>%
  mutate(type = fct_relevel(type, c("S1", "S2", "S3", "S4", "C1", "C2", "TS3")))

res$type

Output:

 [1] S1  S1  S1  S1  S2  S2  S2  S2  S3  S3  S3  S3  S4  S4  S4  S4  C1  C1  C1  C1  C2  C2  C2  C2  TS3 TS3 TS3 TS3
Levels: S1 S2 S3 S4 C1 C2 TS3
Artem
  • 3,304
  • 3
  • 18
  • 41