簡體   English   中英

如何根據數據集中的另一列將數據集中的列分為三組(三分位數)? 使用 R

[英]How to divide column in dataset into three groups (tertiles) based on another column in the dataset? Using R

我無法根據數據集中的另一列將數據集中的列划分為三分位數。 例如,如何根據基因表達水平將基因表達水平分為三組(低、中、高)? 數據集中的列將基因作為一列,將表達作為另一列。

我正在考慮使用這個 function:

排序(數據集名稱$表達式)

因此,這會將表達水平從最高到最低排序。 但是,我不知道如何 label 低、中或高,以及如何為每一個創建新的子集?

提前致謝!

這是使用 R 附帶的 iris 示例數據集的示例。 在這里,三分位數將基於可變花瓣長度。

# generate tertile limits using the quantile function,
# with proportion spacing of 0 to 1 at .33 intervals.
# These 4 values represent the start and end points in terms of Petal Length,
# of the three terriles.
tertile_limits <- quantile(iris$Petal.Length, seq(0, 1, 1/3), na.rm = TRUE)

# use the tertile start and end points (4 points, which creates 3 intervals)
# to create a new factor in the dataset
# The three tertiles are also explicitly labelled Low, Medium, and High, though this is optional.
iris$Petal.Length.Tertiles <- cut(iris$Petal.Length, tertile_limits, c('Low', 'Medium', 'High'), include.lowest = TRUE)

您可以使用quantile function 獲得三分位數,然后使用cut function 分配組。 這是一個使用 mtcars 和 mpg 的示例:

cars <- mtcars
breaks <- quantile(cars$mpg, c(.33, .67, 1))
breaks <- c(0, breaks)
labels <- c('low', 'medium', 'high')
cuts <- cut(cars$mpg, breaks = breaks, labels = labels)
cars <- cbind(cars, cuts)
head(cars)
                   mpg cyl disp  hp drat    wt  qsec vs am gear carb   cuts
Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4 medium
Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 medium
Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1   high
Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1 medium
Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 medium
Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1 medium

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM