我的数据如下:
dat <- structure(list(rn = c("A", "B", "C",
"D", "E"), `[0,25)` = c("40 (replaced)",
"52 (replaced)", "5", "2", "5 (replaced)"), `[25,50)` = c("0 (replaced)",
"0 (replaced)", "0 (replaced)", "0 (replaced)", "0 (replaced)"), `[25,100)` = c("5",
"3", "38", "2", "1"), `[50,100)` = c("0 (replaced)", "0 (replaced)",
"0 (replaced)", "0 (replaced)", "0 (replaced)")), row.names = c(NA,
-5L), class = c("data.table", "data.frame"))
rn [0,25) [25,50) [25,100) [50,100)
1: A 40 (replaced) 0 (replaced) 5 0 (replaced)
2: B 52 (replaced) 0 (replaced) 3 0 (replaced)
3: C 5 0 (replaced) 38 0 (replaced)
4: D 2 0 (replaced) 2 0 (replaced)
5: E 5 (replaced) 0 (replaced) 1 0 (replaced)
我可以简单地按如下方式得出这些数字:
dat <- t(apply(dat, 1, extract_numeric))
dat <- as.data.frame(dat )
dat <- dat %>%
rowwise() %>%
summarise(V1 = V1, freq =list(c_across(-V1))) %>%
rowwise() %>%
mutate(freq = list(freq[which(freq > 0)]))
dat_out <- structure(list(V1 = c(NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_), freq = list(c(40, 5), c(52, 3), c(5, 38), c(2, 2),
c(5, 1))), class = c("rowwise_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -5L), groups = structure(list(.rows = structure(list(
1L, 2L, 3L, 4L, 5L), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame")))
但是如果我想保留文本,我应该怎么做呢?
所需输出:
freq
c("40 (replaced)","5")
c("52 (replaced)","3")
c("5","38")
c("2","2")
c("5 (replaced)","1")