根据 DF 中不同列的计数和百分比创建 table
Create a table from the count and percentage of different columns in a DF
我得到了这个 df
structure(list(patients = 1:10, adm1 = c(1, 1, 1, 1, 1, 1, 1,
1, 1, 1), adm2 = c(0, 1, 1, 0, 0, 1, 1, 0, 0, 1), adm3 = c(0,
0, 1, 1, 0, 0, 0, 1, 0, 1), adm4 = c(0, 0, 0, 0, 1, 0, 0, 0,
1, 0)), class = "data.frame", row.names = c(NA, -10L))
我想要一个这样的table
adm1 adm2 adm3 adm4
No of patients 10 5 3 2
Percentage 100% 50% 30% 20%
试试 colSums
和 colMeans
t(
sapply(
c(no_of_patients = colSums, percentage = colMeans),
function(f) f(df[-1])
)
)
这给出了
adm1 adm2 adm3 adm4
no_of_patients 10 5.0 4.0 2.0
percentage 1 0.5 0.4 0.2
我们可以使用colSums
和colMeans
-
rbind(no_of_patients = colSums(df[-1]),
percentage = colMeans(df[-1]) * 100)
#. adm1 adm2 adm3 adm4
#no_of_patients 10 5 4 2
#percentage 100 50 40 20
我得到了这个 df
structure(list(patients = 1:10, adm1 = c(1, 1, 1, 1, 1, 1, 1,
1, 1, 1), adm2 = c(0, 1, 1, 0, 0, 1, 1, 0, 0, 1), adm3 = c(0,
0, 1, 1, 0, 0, 0, 1, 0, 1), adm4 = c(0, 0, 0, 0, 1, 0, 0, 0,
1, 0)), class = "data.frame", row.names = c(NA, -10L))
我想要一个这样的table
adm1 adm2 adm3 adm4
No of patients 10 5 3 2
Percentage 100% 50% 30% 20%
试试 colSums
和 colMeans
t(
sapply(
c(no_of_patients = colSums, percentage = colMeans),
function(f) f(df[-1])
)
)
这给出了
adm1 adm2 adm3 adm4
no_of_patients 10 5.0 4.0 2.0
percentage 1 0.5 0.4 0.2
我们可以使用colSums
和colMeans
-
rbind(no_of_patients = colSums(df[-1]),
percentage = colMeans(df[-1]) * 100)
#. adm1 adm2 adm3 adm4
#no_of_patients 10 5 4 2
#percentage 100 50 40 20