簡體   English   中英

如何使用向量遍歷 dataframe 中的一組特定列名?

[英]How to loop over a specific set of columns names in a dataframe with the use of a vector?

幾天來我一直在努力解決這個問題,而且我對 R 還是很陌生。 所以我放棄了,我希望你們中的任何人都可以幫助我。

我想計算按我要循環的不同變量分組的特定變量的匯總統計信息。 我不想每次都復制粘貼我的語法並更改分組變量。 我使用了一個for循環並使用了向量lapply (我的不同分組變量被存儲在其中)。

我認為問題在於我的 dataframe 找不到我存儲在向量中的列名。

我的代碼看起來像這樣:

snp_EPA <- c('rs3798713_C', 'rs174550_C', 'rs174574_A', 'rs174448_C') #Vector of grouping variables

for (i in snp_EPA) {
FA %>% group_by(as.name(i)) %>% summarise(FA, bce_c20_5n_3)
} #For loop I tried, didn't work

epa <- lapply(snp_EPA, function(x) {describeBy(FA$bce_c20_5n_3, as.name(x))})
lapply(epa, print) #lapply function I used, still didn't work....

我們確實需要有關您的數據的更多信息以及使用dput(data)的小樣本。 我可以向您展示幾種獲得您想要的東西的方法,這些方法可能會讓您入門。 我將使用 R 附帶的iris數據集:

data(iris)
str(iris)
# 'data.frame': 150 obs. of  5 variables:
#  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
#  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
#  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
#  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
# $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

該數據集包括對三種不同虹膜的 4 次測量。 獲取描述性統計數據的一種簡單方法是使用splitsummary

iris.split <- split(iris, iris$Species)
lapply(iris.split, summary)
# $setosa
#  Sepal.Length    Sepal.Width     Petal.Length    Petal.Width          Species  
#  Min.   :4.300   Min.   :2.300   Min.   :1.000   Min.   :0.100   setosa    :50  
#  1st Qu.:4.800   1st Qu.:3.200   1st Qu.:1.400   1st Qu.:0.200   versicolor: 0  
#  Median :5.000   Median :3.400   Median :1.500   Median :0.200   virginica : 0  
#  Mean   :5.006   Mean   :3.428   Mean   :1.462   Mean   :0.246                  
#  3rd Qu.:5.200   3rd Qu.:3.675   3rd Qu.:1.575   3rd Qu.:0.300                  
#  Max.   :5.800   Max.   :4.400   Max.   :1.900   Max.   :0.600           
# . . . results for other 3 measurements

另一種方法是使用匯總統計功能,為您對數據進行分組。 numSummary RcmdrMisc 中的 numSummary RcmdrMisc是許多可能性之一:

library(RcmdrMisc)   # You will have to install it the first time with `install.packages("RcmdrMisc)`.
numSummary(iris[, -5], groups=iris$Species)
# 
# Variable: Sepal.Length 
#             mean        sd   IQR  0%   25% 50% 75% 100%  n
# setosa     5.006 0.3524897 0.400 4.3 4.800 5.0 5.2  5.8 50
# versicolor 5.936 0.5161711 0.700 4.9 5.600 5.9 6.3  7.0 50
# virginica  6.588 0.6358796 0.675 4.9 6.225 6.5 6.9  7.9 50 
# . . . results for three other measurements.

這些示例使用所有數字列,但您可以 select 僅使用iris[, 1:3]獲取前三列或使用iris[, c(1,4)]獲取第一列和第四列.

暫無
暫無

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

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