R语言 如何结合两个向量

R语言 如何结合两个向量

在这篇文章中,我们将学习如何在R编程语言中结合两个向量。我们可以使用函数 c() 本身来组合两个或更多的向量。在使用函数 c() 时,所有参数都被强制为一个共同的类型,也就是返回值的类型。

语法: c(…)

参数。

  • . .. :要合并的参数

返回: 一个向量

步骤 –

  • 创建要合并的向量
  • 用c()合并它们
  • 显示合并的结果

例1: 相同数据类型的向量将得到输入数据类型的向量作为结果。

a <- c(1, 2, 8) 
b <- c(5, 8, 9, 10) 
c <- c(a,b)
c
  
cat("typeof a", typeof(a), " typeof b", typeof(b),
    "typeof c",typeof(c) , "\n")
  
a <- c("geek","for","geek")
b <- c("hello","coder")
c <- c(a,b)
c
  
cat("typeof a", typeof(a), " typeof b", typeof(b),
    "typeof c",typeof(c) , "\n")
  
a <- c(TRUE, FALSE, NA)
b <- c(TRUE, FALSE)
c <- c(a,b)
c
  
cat("typeof a", typeof(a), " typeof b", typeof(b),
    "typeof c",typeof(c) , "\n")
Bash

输出

[1]  1  2  8  5  8  9 10

typeof a double  typeof b double typeof c double

[1] geek  for   geek  hello coder

typeof a character  typeof b character typeof c character

[1]  TRUE FALSE    NA  TRUE FALSE

typeof a logical  typeof b logical typeof c logical
Bash

当组合双倍和字符、字符和逻辑、双倍和逻辑的向量时, c ( ) 函数分别返回字符、字符、双倍类型的向量。

例2 :

a <- c(1, 2, 8) 
b <- c("hello","coder")
c <- c(a,b)
  
# a vector of type double and b vector of type 
# character result c vector of type character
c
  
cat("typeof a", typeof(a), " typeof b", typeof(b), 
    "typeof c",typeof(c) , "\n")
  
a <- c("geek","for","geek")
b <- c(TRUE, FALSE)
  
# a vector of type character and b vector of type logical
# result c vector of type character
c <- c(a,b)
c
  
cat("typeof a", typeof(a), " typeof b", typeof(b), 
    "typeof c",typeof(c) , "\n")
  
a <- c(1, 2, 8) 
b <- c(TRUE, FALSE)
c <- c(a,b)
  
# a vector of type double and b vector of type 
# logical result c vector of type double
c
  
cat("typeof a", typeof(a), " typeof b", typeof(b),
    "typeof c",typeof(c) , "\n")
Bash

输出

[1] 1     2     8     hello coder

typeof a double  typeof b character typeof c character

[1] geek  for   geek  TRUE  FALSE

typeof a character  typeof b logical typeof c character

[1] 1 2 8 1 0

typeof a double  typeof b logical typeof c double
Bash

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册