📜  提取 R 中向量的每个第 N 个元素

📅  最后修改于: 2022-05-13 01:55:18.924000             🧑  作者: Mango

提取 R 中向量的每个第 N 个元素

在本文中,我们将看到如何在 R 编程语言中从向量中提取每个N元素。

方法一:使用迭代

在声明一个变量的同时对向量执行迭代,计数器初始化为 0。每次迭代,计数器递增,一旦访问第 n 个元素,它就会被打印出来,计数器被重新初始化为 0。结果,获得每个第 n 个索引处的元素序列。这种方法所需的时间复杂度为 O(n),其中 n 是向量的长度。

例子

R
# declaring a vector 
vec <- c(1,2,3,4,5,4,3,7,8,9)
  
# accessing every third element 
# of the vector maintaining counter 
count = 0
  
# looping over the vector elements
for (i in vec){
  
    # incrementing count
    count= count + 1
      
    # checking if count is equal to 
    # third element
    if(count == 3){
          
        # printing the specific element
        print (i)
          
        # reinitialising count to 0 
        count = 0
    }  
}


R
# declaring a vector 
vec <- c("geeks","for","geeks","is","a","unique",
         "portal","to","learn","and","grow")
  
# accessing every second element of 
# the vector 
n = 2
  
# maintaining counter 
count = 0
  
# looping over the vector elements
for (i in vec){
    
    # incrementing count
    count= count + 1
      
    # checking if count is equal to third
    # element
    if(count %% n == 0){
          
        # printing the specific element
        print (i)
    }  
}


R
# declaring a vector
vec <- 5:20
  
print("Original vector:")
print(vec)
  
print("Extracting every 4th element")
  
# iterating over 1 to length of the 
# vector to extract elements
extracted_vec <- vec[seq(1, length(vec), 4)]
  
print ("Resultant elements")
print(extracted_vec)


输出

方法 2:使用迭代和取模

在声明变量的同时对向量执行迭代,计数器初始化为 0。每次迭代时,计数器都会递增,并使用指定的第 n 个元素检查其模数。如果模块操作的结果为 0,则打印该元素。这种方法所需的时间复杂度为 O(n),其中 n 是向量的长度。

例子

电阻



# declaring a vector 
vec <- c("geeks","for","geeks","is","a","unique",
         "portal","to","learn","and","grow")
  
# accessing every second element of 
# the vector 
n = 2
  
# maintaining counter 
count = 0
  
# looping over the vector elements
for (i in vec){
    
    # incrementing count
    count= count + 1
      
    # checking if count is equal to third
    # element
    if(count %% n == 0){
          
        # printing the specific element
        print (i)
    }  
}

输出

方法 3:使用seq()函数

R 中的 seq() 方法用于从它们引用的对象中生成序列。 seq() 方法根据约束提取原始向量的子集,即开始和结束索引,以及每次迭代期间要增加的步数。它根据这些约束访问给定向量索引处的元素,然后将其附加到序列对象。

例子

电阻

# declaring a vector
vec <- 5:20
  
print("Original vector:")
print(vec)
  
print("Extracting every 4th element")
  
# iterating over 1 to length of the 
# vector to extract elements
extracted_vec <- vec[seq(1, length(vec), 4)]
  
print ("Resultant elements")
print(extracted_vec)

输出