了解R

时间:2019-06-20 21:12:57

标签: r list indexing

摘要。 我无法理解有关以下内容的代码单元 列表的子设置。我正在将索引应用于列表。 问题是当我将索引应用于内部的列表时 自定义函数,列表的行为类似于表,返回 仅第一列,但每一行(总共4行)。 如果我将相同的索引应用于该列表之外的相同列表 自定义函数,输出仅是第一个元素 列表,显示包含的字符向量的两个元素 在列表的第一个元素中。我需要知道为什么会有一个 输出差异。

我如何尝试自己解决问题? 我对以下搜索字词执行了Google搜索: [R中的索引列表](索引列表https://stackoverflow.com/questions/tagged/r)。 最近的文章是这篇文章:How to correctly use lists in R。 但是,它无法回答我的问题。

简介。 在陈述问题之前,我引用了我正在使用的代码 因为绝对无法解释这个问题 抽象。

在下面,有四个指示告诉学生 跟随。每个都被枚举。

# Instruction 1:
# Create a character vector containing the names of the top four 
# mathematicians that contributed to the field of statistics and
# list their birth years, with the name and year separated by a
# colon.

mathematicians <- c("GAUSS:1777", "BAYES:1702", "PASCAL:1623", "PEARSON:1857")
# The above code creates a character vector with four elements.

# Instruction 2: Next, use the strsplit() function to split the person's
# last name from his birth year.

split_name_and_year_born <- strsplit(mathematicians, split = ":")
# The variable split_name_and_year_born must be a list because
# strsplit only returns lists (according to the documentation).

# Instruction 3: Write a function that accepts a list or vector
# object and returns only the first element of that object.

first <- function(x) {
   x[1]
}
# This is a fairly straightforward function. If x is a list then
# x[1] should be the first element of that list. The same is true
# for vectors.

# Instruction 4: apply the first function to the list split_name_and_year_born
lapply(split_name_and_year_born, first)
# [[1]]
# [1] "GAUSS"
# 
# [[2]]
# [1] "BAYES"
# 
# [[3]]
# [1] "PASCAL"
# 
# [[4]]
# [1] "PEARSON"

我的评论:如果您将split_name_and_year_born视为长度为2的向量列表,我们可以想象该列表的行为有点像表格,其中第一个元素是表格中的第一列。给定输出,对上面代码的这种解释是有意义的。但是,如果输入以下代码行,则只会得到列表的第一个元素。

split_name_and_year_born[1]

[[1]] [1]“ GAUSS”“ 1777”

我的问题是,为什么输出会有差异?我正在使用相同的数据结构和相同的数据。我只在不同的地方应用索引运算符。为什么输出会有所不同?该函数必须做一些隐式的事情。我就是不知道。

0 个答案:

没有答案