[英]How can I create a function that creates a matrix using values from my dataset in R?
我有一個包含 6 個變量的 120 個觀察值的數據集。 五個變量是因素,1個變量是我的目標變量。 我需要編寫一個 function 它將創建一個矩陣(對於每個因子),其中包含因子的每個級別作為列,目標變量的最大值作為第一行,目標變量的最小值作為第二行.
我知道如何創建一個矩陣,但是當我需要通過 function 制作它時我迷路了。 有人可以幫忙嗎?
這是一個簡單的例子,說明我想用一個虛構的簡單數據集達到什么目的。 例子
如您所見,對於因子的每個級別(在圖片因子1上),我想指示目標的最高值,以及目標的最低值。
這是我自己的數據的一個子集:
> dput(data_plu[1:4, ])
structure(list(NaNO3 = structure(c(2L, 8L, 8L, 3L), .Label = c("10",
"14", "18", "2", "22", "26", "30", "6"), class = "factor"),
CaCl2 = structure(c(4L,
8L, 8L, 8L), .Label = c("0.1", "0.28", "0.46", "0.64", "0.82",
"1", "1.19", "1.37"), class = "factor"), PO4 = structure(c(1L,
5L, 5L, 6L), .Label = c("0.1", "0.8", "1.5", "2.2", "2.9", "3.6",
"4.3", "5"), class = "factor"), NH4Cl = structure(c(5L, 3L, 3L,
6L), .Label = c("0.5", "10.86", "12.93", "15", "2.58", "4.65",
"6.72", "8.79"), class = "factor"), MgSO4 = structure(c(4L, 7L,
1L, 7L), .Label = c("0.21", "0.35", "0.5", "0.64", "0.79", "0.93",
"1.08", "1.22"), class = "factor"), DC = c(15000L, 707500L, 720000L,
872500L)), row.names = c(NA, 4L), class = "data.frame")
您可以修改它以滿足您的需要。 我寫了一個 function 來處理一個因素,然后使用lapply
來處理它們。 我已將您的示例數據稱為dta
:
stats <- function(x, y) {
minmax <- aggregate(y, list(x), range)
cols <- minmax[, 1]
result <- as.matrix(t(minmax[, -1]))
dimnames(result) <- list(c("Min", "Max"), Levels=as.character(cols))
return(result)
}
out <- lapply(dta[, -6], function(x) stats(x, dta$DC))
head(out, 1)
# $NaNO3
# Levels
# 14 18 6
# Min 15000 872500 707500
# Max 15000 872500 720000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.