How to print string vectors vertically in R?



To print string vectors vertically in R, we can follow the below steps −

  • First of all, create a vector.
  • Then, use cat function to print the vector vertically.

Example 1 

Let's create a vector as shown below −

 Live Demo

Alphabets<-LETTERS[1:26]
Alphabets

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T" "U" "V" "W" "X" "Y" "Z"

Print the vector vertically

Using cat function to print the Alphabets vector in vertical form −

 Live Demo

Alphabets<-LETTERS[1:26]
cat(paste("\t",Alphabets,"
",sep ="\""))

Output

“A”
“B”
“C”
“D”
“E”
“F”
“G”
“H”
“I”
“J”
“K”
“L”
“M”
“N”
“O”
“P”
“Q”
“R”
“S”
“T”
“U”
“V”
“W”
“X”
“Y”
“Z”

Example 2

Let's create a vector as shown below −

 Live Demo

US_States<-c("AK", "AL", "AR", "AS", "AZ", "CA", "CO", "CT", "DC", "DE", "FL",
"GA", "GU", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME",
"MI", "MN", "MO", "MP", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV",
"NY", "OH", "OK", "OR", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UM", "UT",
"VA", "VI", "VT", "WA", "WI", "WV", "WY")
US_States

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

[1] "AK" "AL" "AR" "AS" "AZ" "CA" "CO" "CT" "DC" "DE" "FL" "GA" "GU" "HI"
"IA"
[16] "ID" "IL" "IN" "KS" "KY" "LA" "MA" "MD" "ME" "MI" "MN" "MO" "MP" "MS"
"MT"
[31] "NC" "ND" "NE" "NH" "NJ" "NM" "NV" "NY" "OH" "OK" "OR" "PA" "PR" "RI"
"SC"
[46] "SD" "TN" "TX" "UM" "UT" "VA" "VI" "VT" "WA" "WI" "WV" "WY"

Print the vector vertically

Using cat function to print the Alphabets vector in vertical form −

 Live Demo

US_States<-c("AK", "AL", "AR", "AS", "AZ", "CA", "CO", "CT", "DC", "DE", "FL",
"GA", "GU", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME",
"MI", "MN", "MO", "MP", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV",
"NY", "OH", "OK", "OR", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UM", "UT",
"VA", "VI", "VT", "WA", "WI", "WV", "WY")
cat(paste("\t",US_States,"
",sep ="\""))

Output

"AK"
"AL"
"AR"
"AS"
"AZ"
"CA"
"CO"
"CT"
"DC"
"DE"
"FL"
"GA"
"GU"
"HI"
"IA"
"ID"
"IL"
"IN"
"KS"
"KY"
"LA"
"MA"
"MD"
"ME"
"MI"
"MN"
"MO"
"MP"
"MS"
"MT"
"NC"
"ND"
"NE"
"NH"
"NJ"
"NM"
"NV"
"NY"
"OH"
"OK"
"OR"
"PA"
"PR"
"RI"
"SC"
"SD"
"TN"
"TX"
"UM"
"UT"
"VA"
"VI"
"VT"
"WA"
"WI"
"WV"
"WY"

Advertisements