【问题标题】:R) Having trouble finding numbers in ArraysR) 在数组中查找数字时遇到问题
【发布时间】:2021-04-23 17:47:28
【问题描述】:

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)查看 HairEyeColor,我能够看到 32 行的数组?(矩阵?)所以我尝试了 nrow(HairEyeColor) for e)(i),但它没有用。对于 e) 的其他问题,我还需要帮助。

【问题讨论】:

    标签: r arrays matrix


    【解决方案1】:

    您可以查看数组的结构以了解 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 只是对条目进行汇总。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      • 1970-01-01
      • 2015-04-25
      • 1970-01-01
      • 2017-05-02
      相关资源
      最近更新 更多