R语言 把三个数组与给定条件结合起来
在这篇文章中,我们将讨论如何在R编程语言中用给定的条件组合三个数组。让我们来看看这样一个条件:第一个数组的第一行后面是第二个数组的第一行,然后是第三个数组的第一行。
在R语言中可以使用rbind()操作创建数组向量,将各行绑定在一起。R中的行绑定操作会创建一个包含指定行数的矩阵。类似地,可以创建n个数组。然后应用cbind()操作,将数组向量作为参数。它创建了一个合并的矩阵,使用列进行合并。
cbind(arr1, arr2, arr3..)
然后将t()方法应用于结果上,以创建所获输出的转置。然后,行和列被反转,产生一个转置矩阵。然后在输出上应用矩阵操作,其中
语法: matrix ( data, ncol, byrow)
参数 :
- data – 要转换为矩阵的数据
- ncol – 在结果矩阵中要产生的列数
- byrow – 逻辑上的。如果是FALSE(默认值),矩阵将按列填充,否则矩阵将按行填充。
例1 :
# creating array1
arr1 = rbind(rep("Geeks", 3), rep("For", 3), rep("Geeks", 3))
print("Array 1 : ")
print(arr1)
# creating array2
arr2 = rbind(rep("Learn", 3), rep("Computer", 3),
rep("Programming", 3))
print("Array 2 : ")
print(arr2)
# creating array3
arr3 = rbind(rep("Coding", 3), rep("is", 3), rep("fun", 3))
print("Array 3 : ")
print(arr3)
# combing arrays together
comb_arr = matrix(t(cbind(arr1, arr2, arr3)), ncol=3, byrow=T)
# printing the combined matrix
print("Combined array is : ")
print(comb_arr)
输出
[1] "Array 1 : "
[,1] [,2] [,3]
[1,] "Geeks" "Geeks" "Geeks"
[2,] "For" "For" "For"
[3,] "Geeks" "Geeks" "Geeks"
[1] "Array 2 : "
[,1] [,2] [,3]
[1,] "Learn" "Learn" "Learn"
[2,] "Computer" "Computer" "Computer"
[3,] "Programming" "Programming" "Programming"
[1] "Array 3 : "
[,1] [,2] [,3]
[1,] "Coding" "Coding" "Coding"
[2,] "is" "is" "is"
[3,] "fun" "fun" "fun"
[1] "Combined array is : "
[,1] [,2] [,3]
[1,] "Geeks" "Geeks" "Geeks"
[2,] "Learn" "Learn" "Learn"
[3,] "Coding" "Coding" "Coding"
[4,] "For" "For" "For"
[5,] "Computer" "Computer" "Computer"
[6,] "is" "is" "is"
[7,] "Geeks" "Geeks" "Geeks"
[8,] "Programming" "Programming" "Programming"
[9,] "fun" "fun" "fun"
例2 :
# creating array1
arr1 = cbind(rep("Row", 1), rep("No.", 1), rep("1", 1))
print("Array 1 : ")
print(arr1)
# creating array2
arr2 = cbind(rep("Row", 1), rep("No.", 1), rep("2", 1))
print("Array 2 : ")
print(arr2)
# creating array3
arr3 = cbind(rep("Row", 1), rep("No.", 1), rep("3", 1))
print("Array 3 : ")
print(arr3)
# combing arrays together
comb_arr = matrix(t(cbind(arr1, arr2, arr3)),
ncol=3, byrow=T)
# printing the combined matrix
print("Combined array is : ")
print(comb_arr)
输出
> #creating array1
> arr1 = cbind(rep("Row",1), rep("No.",1), rep("1",1))
> print("Array 1 : ")
[1] "Array 1 : "
> print(arr1)
[,1] [,2] [,3]
[1,] "Row" "No." "1"
> #creating array2
> arr2 = cbind(rep("Row",1), rep("No.",1), rep("2",1))
> print("Array 2 : ")
[1] "Array 2 : "
> print(arr2)
[,1] [,2] [,3]
[1,] "Row" "No." "2"
> #creating array3
> arr3 = cbind(rep("Row",1), rep("No.",1), rep("3",1))
> print("Array 3 : ")
[1] "Array 3 : "
> print(arr3)
[,1] [,2] [,3]
[1,] "Row" "No." "3"
> #combing arrays together
> comb_arr = matrix(t(cbind(arr1,arr2,arr3)),ncol=3, byrow=T)
> print("Combined array is : ")
[1] "Combined array is : "
> #printing the combined matrix
> print(comb_arr)
[,1] [,2] [,3]
[1,] "Row" "No." "1"
[2,] "Row" "No." "2"
[3,] "Row" "No." "3"