2

As I am just starting to learn the R, I want to re write the below code into the pipe operator way. however, the setting rowname and colname blocked me. I will be grateful if some one can help me, which is highly appreciated!

The original code is detailed as below,

data_3 <- c(692, 5, 0, 629, 44, 9)
table_3 <- matrix(data_3, ncol=3, byrow = TRUE)
colnames(table_3) <- c("Improved", "Hospitalized", "Death")
rownames(table_3) <- c("Treated", "Placebo")
table_3 <- as.table(table_3)

chisq.test(table_3)
fisher.test(table_3)

however, I got into trouble in the setting the colname and rowname when I tried to use the pipe operator.

c(692, 5, 0, 629, 44, 9) %>% 
  matrix(ncol = 3) %>% 
  colnames <- c("Improved", "Hospitalized", "Death")

I will be grateful if anyone could help me in this pipe operator using.

your support is highly appreciated!

Best regards,

Charles

charles
  • 77
  • 3

2 Answers2

6

I suggest:

c(692, 5, 0, 629, 44, 9) |>
  matrix(ncol = 3) |> 
  as.data.frame() |>
  setNames(c("Improved", "Hospitalized", "Death"))

notes/unsolicited advice

  • I used the native R pipe (|>) so I wouldn't have to load magrittr (or dplyr or tidyverse). (Native pipes are not quite the same as %>% but they work very similarly.)
  • I converted the matrix into a data frame; data frames have a "names" (the same as their column names) attribute, where matrices only have "colnames"; setNames() allows you to use a "regular" function (rather than a weird replacement function, i.e. colnames<-). If you were going to do this a lot but really didn't want to convert your matrix to a data frame, you could define
set_col_names <- function(x, nm) {
   colnames(x) <- nm
   return(x)
}

(which would be marginally less efficient but easier to read)

  • my personal opinion is that this example overuses pipes. Pipes are great, but beyond a certain point they make the code (to me) more obscure rather than clearer (but this example isn't as bad as, say, 3 %>% `+`(5) ...)
  • In real life I would probably write this code as
matrix_3 <- matrix(c(692, 5, 0, 629, 44, 9),
                 ncol=3, byrow = TRUE,
                 dimnames = list(c("Treated", "Placebo"),
                                 c("Improved", "Hospitalized", "Death")))
table_3 <- as.table(matrix_3)

(I might use a pipe for the last step.)

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • Thank you for your great advice. I have to say I may a bit overuse the pipe for my practice. your advice is highly appreciated! – charles Jan 22 '22 at 12:00
2

You want to do:

`colnames<-`(c("Improved", "Hospitalized", "Death"))

Note the backticks and no spaces as colnames<- is actually a function.

Brian Montgomery
  • 2,244
  • 5
  • 15
  • thank you so much for your prompt reply. by the way, any recommend material for my learning pipe is highly appreciated! – charles Jan 22 '22 at 12:02