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
I suggest:
c(692, 5, 0, 629, 44, 9) |>
matrix(ncol = 3) |>
as.data.frame() |>
setNames(c("Improved", "Hospitalized", "Death"))
|>) 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.)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 defineset_col_names <- function(x, nm) {
colnames(x) <- nm
return(x)
}
(which would be marginally less efficient but easier to read)
3 %>% `+`(5) ...)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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With