簡體   English   中英

R) 在 Arrays 中查找數字時遇到問題

[英]R) Having trouble finding numbers in Arrays

a) 在講座中,我們創建了一個名為 HairEyeColor 的矩陣。 將此矩陣重命名為 HairEyeColor1。 b) 從您的全局環境中刪除 HairEyeColor。 c) 在 RStudio 數據集中,找到名稱為 HairEyeColor 的數據集。 查看數據集。 d) 編寫代碼來檢查 HairEyeColor 是一個數組。 e) 編寫代碼以確定: (i) 調查中的受訪者總數。 (ii) 調查中男性受訪者的總數。 (iii) 有多少受訪者有藍眼睛? (iv) 有多少女性受訪者有紅頭發?

上面是我被賦予的代碼,下面是我嘗試過的。

# Construct a vector of the data to be used in the matrix
HEC <- c(32, 11, 10, 3, 53, 50, 25, 15, 3, 30, 5, 8)
# Construct the matrix HairEyeColor
HairEyeColor <- matrix(HEC, nrow = 3, ncol = 4, byrow = TRUE) # fill by row

# a) renaming the matrix to HairEyeColor1
HairEyeColor1 <- HairEyeColor
# b) Removing HairEyeColor from Global Environment.
rm(HairEyeColor)
# c) view HairEyeColor.
View(HairEyeColor)
# d) Writing code to check that HairEyeColor is an array.
is.array(HairEyeColor)
# e) Writing code to determine:
# (i) the total number of respondents in the survey. 
# (ii) the total number of male respondents in the survey. 
# (iii) How many respondents have blue eyes? 
# (iv) How many female respondents have red hair? 

從 c)viewing HairEyeColor,我可以看到 arrays?(matrix?) 有 32 行,所以我嘗試了 nrow(HairEyeColor) for e)(i) 但它沒有用。 對於 e) 的其他問題,我還需要幫助。

您可以查看數組的結構以找出 3 個維度中的每個維度的含義。

str(HairEyeColor)

'table' num [1:4, 1:4, 1:2] 32 53 10 3 11 50 10 30 10 25 ...
 - attr(*, "dimnames")=List of 3
  ..$ Hair: chr [1:4] "Black" "Brown" "Red" "Blond"
  ..$ Eye : chr [1:4] "Brown" "Blue" "Hazel" "Green"
  ..$ Sex : chr [1:2] "Male" "Female"

所以第一個維度有 4 個頭發等級,第二個維度有 4 個眼睛顏色等級,第三個維度有 2 個性別等級。

 # e) Writing code to determine:
# (i) the total number of respondents in the survey.
sum(HairEyeColor)
# (ii) the total number of male respondents in the survey.
sum(HairEyeColor[,,"Male"])
# (iii) How many respondents have blue eyes? 
sum(HairEyeColor[,"Blue",])
# (iv) How many female respondents have red hair? 
sum(HairEyeColor["Red",,"Female"])

這應該是不言自明的,您可以通過在適當的位置 [x,x,x] 中放入不同的字符因子級別來訪問不同的維度。 Sum 只是對條目進行總結。

暫無
暫無

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

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