这是dplyr 和caTools::trapz 的一种方法:
首先,我们需要获取当前停留在列名中的时间。为了方便,我们可以使用readr::parse_number:
readr::parse_number(names(data))
[1] 0 10 20 30 40 50 60
从那里,我们可以使用caTools::trapz。它需要两个参数,x 和 y。我们可以使用dplyr 将函数应用于rowwise 和c_across 的整行。
library(dplyr)
library(readr)
library(caTools)
data %>%
rowwise() %>%
mutate(AUC = trapz(parse_number(names(cur_data())),c_across()))
# Rowwise:
CASET0 T10 T20 T30 T40 T50 T60 AUC
<int> <int> <int> <int> <int> <int> <int> <dbl>
1 88 89 91 105 107 139 159 6545
2 92 NA 102 NA NA 189 144 NA
3 79 NA 82 98 106 140 118 NA
4 81 81 82 92 86 101 124 5445
5 90 89 89 106 115 134 101 6285
6 91 77 87 82 95 133 156 5975
或处理 NA:
data %>%
rowwise() %>%
mutate(AUC = trapz(parse_number(names(cur_data()))[!is.na(c_across())],
c_across()[!is.na(c_across())]))
# Rowwise:
CASET0 T10 T20 T30 T40 T50 T60 AUC
<int> <int> <int> <int> <int> <int> <int> <dbl>
1 88 89 91 105 107 139 159 6545
2 92 NA 102 NA NA 189 144 7970
3 79 NA 82 98 106 140 118 6050
4 81 81 82 92 86 101 124 5445
5 90 89 89 106 115 134 101 6285
6 91 77 87 82 95 133 156 5975
有关更多提示,请参阅dplyr rowwise tutorial。
或者,您可以使用带有apply 的基本 R 方法:
apply(data,1,function(x) trapz(as.numeric(gsub("[^0-9]+","",names(data)))[!is.na(x)],
x[!is.na(x)]))
1 2 3 5 8 9
6545 7970 6050 5445 6285 5975
数据:
data <- structure(list(CASET0 = c(88L, 92L, 79L, 81L, 90L, 91L), T10 = c(89L,
NA, NA, 81L, 89L, 77L), T20 = c(91L, 102L, 82L, 82L, 89L, 87L
), T30 = c(105L, NA, 98L, 92L, 106L, 82L), T40 = c(107L, NA,
106L, 86L, 115L, 95L), T50 = c(139L, 189L, 140L, 101L, 134L,
133L), T60 = c(159L, 144L, 118L, 124L, 101L, 156L)), class = "data.frame", row.names = c("1",
"2", "3", "5", "8", "9"))