Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe operator using in R [duplicate]

Tags:

r

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

like image 935
charles Avatar asked Feb 26 '26 19:02

charles


1 Answers

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.)

like image 113
Ben Bolker Avatar answered Feb 28 '26 11:02

Ben Bolker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!