Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to convert columns of an R data frame into a single vector?
Sometimes all the columns in a data frame have similar data characteristics representing a particular variable. For example, having a data frame containing five columns each with heights of people. To convert this type of data frame into a vector we can use as.vector function along with the as.matrix function. The as.matrix will read the data frame columns so that the array of values can be created.
Example1
y1<−sample(LETTERS[1:26],20) y2<−sample(LETTERS[1:26],20) y3<−sample(LETTERS[1:26],20) y4<−sample(LETTERS[1:26],20) df2<−data.frame(y1,y2,y3,y4) df2
Output
y1 y2 y3 y4 1 G V P Y 2 A J N A 3 E L X L 4 K E B O 5 P Z O E 6 W T T Z 7 X N J U 8 L D L J 9 U U Z X 10 Y B A F 11 F M W I 12 Q P F B 13 T Y H M 14 H C K T 15 I F Y W 16 N G G H 17 R A M K 18 S K E G 19 C O U Q 20 O W D V
Converting df2 to a vector −
Example
df2_vector<−as.vector(as.matrix(df2[,c("y1","y2","y3","y4")]))
df2_vector
Output
[1] "G" "A" "E" "K" "P" "W" "X" "L" "U" "Y" "F" "Q" "T" "H" "I" "N" "R" "S" "C" [20] "O" "V" "J" "L" "E" "Z" "T" "N" "D" "U" "B" "M" "P" "Y" "C" "F" "G" "A" "K" [39] "O" "W" "P" "N" "X" "B" "O" "T" "J" "L" "Z" "A" "W" "F" "H" "K" "Y" "G" "M" [58] "E" "U" "D" "Y" "A" "L" "O" "E" "Z" "U" "J" "X" "F" "I" "B" "M" "T" "W" "H" [77] "K" "G" "Q" "V"
Advertisements
