วันพุธที่ 6 พฤษภาคม พ.ศ. 2563

โครงสร้างควบคุม ใน R

โครงสร้างควบคุม (Control Structures)


โครงสร้างควบคุมใช้เพื่อควบคุมการไหลของประโยคคำสั่งที่ถูกสั่งให้ทำงานโดยตัวแปลของ R  โดยรวมประโยคคำสั่งเงื่อนไขและลูป  R คำนวณตามคำสั่งประโยคคำสั่งเหล่านั้นตามลำดับโดยคำนวนหาค่า ประโยคคำสั่งสามารถจัดให้อยู่แยกกันโดยใช้เซมิโคลอนคั่นหรือไม่ก็ขึ้นบรรทัดใหม่  เซมิโคลอนนำมาใช้เพื่อสร้างประโยคคำสั่งที่แยกจากกัน เป็นการช่วยตัวแปลเพื่อแยกแยะประโยคคำสั่ง และทำให้สามารถเข้าใจประโยคคำสั่งได้ดีขึ้น และอ่านง่ายขึ้นกว่าเดิมสำหรับโปรแกรมเมอร์  ทั้งเซมิโคลอน และ บรรทัดใหม่ที่จัดวางไว้ตอนท้ายประโยคคำสั่ง ถ้าประโยคคำสั่งไม่สมบูรณ์  ตัวแปลจะปล่อยไว้ไม่สนใจว่าถ้า ส่วนการโปรแกรมนี้อยู่ในภาวะปฏิสัมพันธ์หรือไม่ เครื่องหมายเตรียมพร้อมจะเปลี่ยนจากหัวลูกศรทางขวา(>) ไปเป็นเครื่องหมายบวก (+).

ตัวอย่างต่อไปแสดงส่วนการโปรแกรม (session) ตอบสนองเมื่ออยู่ในภาวะปฏิสัมพันธ์
> x <- 0; x + 7
[ 1] 7

เมื่อตัวแปลตรวจสอบประโยคคำสั่งหนึ่งสมบูรณ์แล้ว ตัวแปลคำนวณตามคำสั่งแล้วคือกลับให้ค่าหนึ่ง  ผลลัพธ์ที่ให้คืนกลับมาพิจารณาเป็นค่าของประโยคคำสั่ง ที่ค่านี้สามารถกำหนดให้กับสัญลักษณ์  ประโยคคำสั่งภายใต้โครงสร้างควบคุมจัดกลุ่มด้วยวงเล็บปีกกาเปิด ({) และวงเล็บปีกกาปิด(}). ประโยคคำสั่งที่อยู่ในวงเล็บจะเรียกว่าบล็อก บล็อกจะถูกอ่านหลักจากปิดวงเล็บปีกกา ประโยคคำสั่งหนึ่งจะถูกอ่านเข้ามา เมื่อบรรทัดใหม่ถูกสร้างขึ้นที่ท้ายประโยคคำสั่งที่สมบูรณ์.  เหมือนในนัทเชลล์หนึ่ง (a nutshell),ประโยคคำสั่งที่อ้างถึงประโยคคำสั่งเดี่ยวหรือบล็อกหนึ่ง  ต่อไปเป็นตัวอย่างหนึ่งของประโยคคำสั่งหนึ่งที่ปิดล้อมด้วยวงเล็บ
> { x <- 0
> + x + 4 }
     [1] 4

R ใช้โครงสร้างควบคุม if, if/else, while, repeat, และ for เพื่อให้เกิดผลสำหรับประโยคคำสั่งเงื่อนไขและทำงานซ้ำ  ไวยากรณ์ต่อไปนี้จะแสดงให้เราถึงการเขียนโครงสร้างควบคุมในการประยุกต์ใช้

     if -- if (เงื่อนไข) นิพจน์; ตัวอย่างเช่น:
if(x>y)
{ print (X is greater than Y) }

     if/else – if (เงื่อนไข) นิพจน์1 else นิพจน์2; ตัวอย่างเช่น:
if (2==1) {print(Yes)}
else print(No)

     while – while(เงื่อนไข) นิพจน์; ตัวอย่างเช่น:
x <- 1
while(x < 4)
{ x <- x + 2 print(x)}

     repeat – repeat นิพจน์; ตัวอย่างเช่น:
x <- 1
repeat { x <- x + 1
print(z) break() }

     for – for (variables in sequence) statement; ตัวอย่างเช่น
for (value in seq(0,1,by=0.3))
{ result(value,"\n"); }

นิพจน์เหล่านี้ในโครงสร้างควบคุมข้างบนนี้ปกติแล้วอ้างถึงนิพจน์แบบคอมปาวด์ (compound expressions) ใน while, repeat และ สำหรับการก่อเกิดลูป เราสารมารถใช้ break ที่จะหยุดทำงานของลูป และต่อไปเพื่อไปต่อการทำงานซ้ำต่อไป(การซ้ำกระบวนการ). การเกิดโครงสร้างทำงานซ้ำ “if”, “while”, “repeat”, “for”, “break”, และ “next” ถูกเก็บไว้ภายในของฟังก์ชัน.

การสั่งปฏิบัติงานตามเงื่อนไขและการทำงานซ้ำ (Conditional  and repeat Execution)

ใน R ใช้ การสร้างเงื่อนไขและทำงานซ้ำเพื่อหาค่าเดี่ยวและหลายค่า  โดยใช้ประโยคคำสั่งของ “if” และ “if/else” เพื่อหาค่าเงื่อนไขหนึ่งเพื่อทำให้เกิดผลลัพธ์ที่ถูกต้อง

การสั่งปฏิบัติตามเงื่อนไข Conditional Execution
การให้ปฏิบัติตามเงื่อนไขเป็นการสร้างตามเงื่อนไขที่ใช้ไวยากรณ์ต่อไปนี้
if (นิพจน์1) นิพจน์2 else นิพจน์3  ไวยากรณ์ “if/else” แสดงให้เห็นถึง“นิพจน์ion1” ต้องถูกคำนวณหาค่าได้ผลเป็นค่าหนึ่ง  ตัวกระทำAND(&&) และ OR(||) บ่อยครั้งที่ใช้ในประโยคคำสั่ง“if”  สำหรับสัญลักษณ์ตัวกระทำเดี่ยวAND(&) และOR(|)  ในอีกทางหนึ่งประยุกต์ใช้กับเว็คเตอร์บนฐานขององค์ประกอบเวคเตอร์  ตัวกระทำ AND (&&) และOR (||)   อย่างไรก็ตามเมื่อประยุกต์ใช้กับเวคเตอร์ที่มีความยาวเดียว และเฉพาะคำนวณหาค่านิพจน์ที่2 ถ้าจำเป็น  R ใช้เว็คเตอร์เป็นฐาน  โครงสร้าง if/else ที่เกิดขึ้นเรียกว่าฟังก์ชัน ifelse  อย่างหนึ่ง โดยใช้ไวยากรณ์ดังต่อไปนี้
 ifelse(condition, x, y) 
ฟังก์ชัน “ifelse” คืนกลับเป็นเวคเตอร์หนึ่งด้วยความยาวของอาร์กูเมนต์ที่ยาวที่สุด  ประกอบด้วยองค์ประกอบ elements a[i] และ  b[i], ที่ซึ่ง [i] เป็นจริง, else สั่งปฏิบัติ b[i].

ปฏิบัติคำสั่งทำงานซ้ำ (Repetitive Execution)
กาปฏิบัติคำสั่งทำงานซ้ำเกี่ยวข้องกับ โครงสร้าง for loops, repeat และ while .
 “for” loop ใช้ไวยากรณ์ดังนี้
      for (variable_name in expression1) expression2 

ไวยากรณ์ “for” loop จะมีตัวแปรลูป เป็นเหมือน “variable_name” และนิพจน์เวคเตอร์เป็นเหมือน                    “ expression1”.  นิพจน์เว็คเตอร์มักจะมีลำดับที่เห็นเป็น1:20(1 row; 20 vectors). นิพจน์ที่เป็นกลุ่มคือ  “expression2”, ซึ่งถูกตีซ้ำผ่านตามค่าของผลลัพธ์เว็คเตอร์ใน “expression1”. ถ้าเรามีตัวอย่างหนึ่งและเรามี“vec” เป็นเหมือนเว็คเตอร์หนึ่งของ class indicators.  ถ้าเราประสงค์ที่จะสร้างการพล็อตการแยก x และ y
ในคลาส  เราคงจะใช้ฟังก์ชัน coplot()  นี่เป็นการสร้างอะเรย์หนึ่งของการพล็อตที่สอดคล้องกับแต่ละระดับ ของแฟคเตอร์นั้น  เราคงทำเช่นนี้ด้วยเช่นกันโดยการใช้การพล็อตทั้งหมดในการแสดงผลครั้งเดียว

 ตัวอย่างต่อไปนี้แสดงวิธีการใช้การพล็อตทั้งหมดต่อการแสดงผลครั้งเดียวได้อย่างไร
 > xc <- split(x, vec)
 > yc <- split(y, vec)
      for (i in 1:length(yc))
      { plot(xc[[i]], yc[[i]])
        abline(lsfit(xc[[i]], yc[[i]])) }

ฟังก์ชัน split() สร้างรายการของเว็คเตอร์ ที่ทำให้ได้มาซึ่งการแยกเว็คเตอร์ที่โตกว่าบนฐานของคลาสกำหนดโดยเว็คเตอร์  ฟังก์ชันนี้มักจะใช้ใน boxplots.

        สำคัญ: ในโค๊ด R  “for” loops ไม่ได้ใช้เป็นปกติทั่วไปในภาษาแบบคอมไพล์  โค๊ดเมื่อมองที่ออฟเจ็ค                              ทั้งหมด  ปรากฏว่าเร็วกว่าดีกว่า 

อีกชนิดหนึ่งของลูปที่ใช้ใน R รวมทั้งประโยคคำสั่ง repeat และ while   ประโยคคำสั่ง break นำมาใช้กับลูปเพื่อหยุด/จบ การกระทำ  เป็นหนทางเดียวที่เราสามารถหยุดการทำงานซ้ำของลูป  ประโยคคำสั่งต่อไปที่่นำมาใช้จบไซเคิลเฉพาะ และเคลื่อนไปยัง“next”

หมายเหตุ: ประโยคคำสั่งควบคุมปกติแล้วใช้กับฟังก์ชัน

การ่่ทำงานซ้ำ Iteration 
ในตอนนี้เราจะเรียนรู้เกี่ยวกับการทำงานซ้ำพอสังเขป This is an important topic for programmers because it is used to control the flow of elements within a program, as well as analyzing data. In data analysis iterative statements powers procedures for calculating complex datasets and advanced mathematical calculations relating to statistics. Loops and Vectorization R allows you to create loops and calculate vectors using iteration in R. Loops are used to repeat an operation for a specific number of times. In the following example, you will see how a simple for loop is created. > for (i in 1:n) > { cat("Name #", i, "\n") } [1] Name # 1 Name # 2 Name # 3 Name # 4 In the above example of the for loop, the counter is set and the loop runs for “n” number of times. The result shows that the loop iterated 4 times. The loop actually created one line of output for each value of n=(1, 2, 3) that is passed through the index “I”. The final element in the in the string concatenation is “\n” – a new line break is implemented. This example shows how iteration works with a for loop. You will learn more about “for” loops later on in this chapter. The example can be replaced by applying the function with the three elements of the vector I, , 2, 3. 4. You can do this because the paste() function is vectored. This method can be used to substitute looping in many situations. In the above example, you would replace “cat("Name #" , i, "\n")” with “paste(Country #” , 1:4)”. This is vectored approach. The while loop is similar to the “for” loop and uses iteration until a condition is either true or false. You may also say that the while loop condition is true until it is not. Pay close attention when writing the conditions, because the loop can iterate indefinitely. An indefinite loop is only necessary under special circumstances. Here is an example of a while loop: i <- 5 while (i > 0) { print(i <- i - 1) } [1] 4 [1] 3 [1] 2 [1] 1 [1] 0 // output In the above example of the while loop, the counter is set (i<-5) and is decreased by 1 until it gets to 0. There are more complex ways to solve problems with while loops, like searching for the solution to a “finding-the-number” fame. This is called the “brute force” approach (no shortcuts). You will learn more about writing while loops later on in this chapter. There are other loops that are sequentially exhaustive and can become very intensive to calculate when they iterate through arrays with values. When this happens, you may need to optimize the code and use several processors to reduce the response time of the loop. You can iteratively execute a loop or vectorize the loop. Most loops can be replaced with vectorization because it is more efficient to manage the data this way. Vectorized functions are used in R because they run faster than memory-intensive loops with built-in code. The idea is to apply a specific function instead of instructing R to apply the function separately. The following examples will show you how to write an iterative loop and a vectorized loop. // An iterative loop square i, square i + 1, square i + 2, for (i in 1:2) print(i^2) [1] 1 [1] 4 // A vectorized loop define i = { 1, 2 } (1:2)^2 [1] 1 4 In the above example, the vector is 1, 2. The square function is used to evaluate the vectors, which returns the results for the vector. Be aware that many of the functions in R accept vectors as arguments, which makes it easier to calculate. This helps to resolve potential conflicts. In the following examples, you will see how combination vectors are used. // This example shows two possible conflicts in a single combination. prod(1:2)/prod(1:2) [1] 1 // This example shows 3 possible combinations. prod(1:3)/(prod(1:2) * prod(1:1)) [1] 3 //This example shows 6 possible combinations. prod(1:4)/(prod (1:2) * prod(1:2)) [1] 6 The structure of this function is called the “explosive roommate function”. It looks at the number of potential conflicts that is possible with each “roommate” that is affecting the other. The code calculates the value using the following equation: \(\frac{n!}{k!(n-k)!}\), where \(n\) is the number of roommates and \(k = 2\). The function can be used to calculate increasing numbers. You can also plot part of the function by creating a vector of values and apply the combinations. It is done by using the sapply() function. This is the vectorized equivalent of the “for” loop. The following example shows the “explosive roommate function” written by Francis Smart. // Explosive roommates function. explosive_roommates = function(n) prod(1:n) / (prod(1:2) * prod(1:max(n - 2, 1))) The “explosive roommates function” is applied first when returning a vector of results. The sapply() function is then used to go through the vector of values x and return a vector of results y. This is demonstrated below in the following examples. Step 1: The vector of the x value is defined. x = 2:20 Step 2: The sapply() function is used to establish vectors of y values. y = sapply(x , explosive_roommates) Step 3: The function plots y against x. qplot(x, y, geom = c("line", "point")) + labs(y = "Number of potential conflicts", x = "Number of roommates") Note: You can test the above steps in R to see the results. Make sure that you declare the “explosive roommates function” before you enter them. Looping Looping is an advanced concept in R and can be challenge for those who are new to programming. R has looping structures like any other programming language that requires time and effort to master. Looping is a repeated evaluation for a block of statements. The traditional for, while, and repeat loops are used to evaluate statements, but there are other constructs that are used to control the evaluations. There is an unconventional repeat loop and a family of loops called “apply”, “sapply”, “lapply”, and “tapply”. These are used for implicit looping. Traditional loops like for and while loops are used for repetitive actions, but the Apply loop family are used in specific circumstances, such as in ragged arrays. You can also use loops within loops, for example you can use a “while” loop within a “for” loop. The for, while, and repeat loops are used in R for explicit looping. To control the loops R uses the next and break built-in constructs during an evaluation. The break statement allows you to exit the loop that is currently being executed. The next statement allows you to return to the beginning of the loop to execute the next iteration of the loop. Any statements that are below the statement in this instance will not be evaluated. After an evaluation, loops will return the value of the last statement that was evaluated. You can also assign the results from the for, while, and repeat statements to a symbol. Looping is not necessary in all operations. You can use vectors that do not require a loop. Values that are returned by loop statements are always NULL, which is not generally noticeable. Here is some background information that will help you understand how loops work in R: 1. Loops are slow in R. Although they are slow loops will accomplish the task in reasonable time unless you are working with a large dataset. If you are working with lots of data, there ways to get around it. 2. R is written in a C or some variant of C++ type language. When you execute an R code, you are actually executing C code. R uses the underlying C code to run loops with or without vectors. 3. R provides alternative functions that you can use instead of using loops. The “apply” function for example, works faster than the “for” loop because it actually has built-in for loop written in R. There are also other functions in the apply family that runs faster than loops. However, a well-constructed loop can run just as fast as apply functions. When programming in R, you may encounter a problem within a loop. If this happens refer to the following key points: 1. Reset the set values – You may have to reset the value or a vector within the loop. It is possible that you may have used a statement within the “for” loop that has a value that needs to reset. 2. Missing brackets – Sometimes you may have forgotten to put in your square brackets or curly braces within the counter or to the left or right of the statement. If/Else Statement The if/else statement is conditional and evaluates two or more statements. The arguments within the if” statement is a logical expression. It is a single block of code, where more blocks can be added after the else statement. It is used to evaluate a logical value. If the value is valid, the first statement is evaluated, and if the first statement is NOT TRUE, then the second statement is evaluated. A value is then returned. The following is the syntax for the if/else statement: > if ( statement1=TRUE) > (result1) > else > result3 Here is an example of an “if/else” statement. > x <- 3 > if(x == 5) { print(1) } > else { print(2) } [1] 2 The first “if” statement (x == 5) in the above example is evaluated to produce a value. If the value is TRUE in the first statement, the second statement (print (1)) is evaluated. If the first statement (x==5) is FALSE, the second statement (print(1)) is ignored and the third statement (print(2)) is evaluated. If the value is not logical or valid, an error is returned. If/else statements are used to prevent numeric problems, such as the logarithm of a negative number. Since if/else statements are the same as other statements you can assign values to them. In the following “if/else” examples, both statements produce the same results. if( any(y <= 1) ) y <- log(1+y) else x <- log(y) x <- if( any(y <= 1) ) log(1+y) else log(y) The else clause in both examples is optional. Instead, the statement if (any(y<=1)) y <- y[y <= 1] can be used without the else clause. When the “if“ statement is not within the block and the else is present, you must have the second statement on the same line. If not, the new line at the end of second statement completes the “if“ statement and returns a complete evaluated statement. The easiest way to resolve this is to insert open and close braces ({ }) for compound statements and by placing the else on the same line as the closing brace (}). The closing brace specifies the end of the statement. The following ‘if/else” syntax shows how you would nest compound or multiple statements: if ( statement1 ) { statement2 } else if ( statement3 ) { statement4 } else statement6 The even numbered statements in the example are evaluated and return a value. If the else clause is ignored and the odd numbered statements return FALSE, then no other statements are evaluated and a NULL value is returned. The odd numbered statements are evaluated in order until one of them returns TRUE. The even numbered statements are then evaluated. In the above example, statement4 is only evaluated if statement1 returns FALSE. R allows you to write multiple “if” statements in a conditional form. The first statement/expression is evaluated and returns a single logical value. It allows you to use double AND (&&) and OR (||) operators with the conditional “if” statements. You can use the following operators to produce “TRUE” or “FALSE”, “T” or “F”, “1” or “0” results in if statements. x == y -- This means x is equal to y, for example: if (10 == 5 + 5) print(Yes) x != y -- This means x is not equal to y, for example: if (10 ! = 5 + 5) print(No) x > y -- This means x is greater than y, for example: if (10 > 5 ) print(It is greater) x < y -- This means x is less than y, for example: if (10 < 5) print(It is not greater) x <= y -- This means x is less than or equal to y, for example: if (10 <= 5 + 5) print (It is equal) x >= y -- This means x is greater than or equal to y, for example: if (5 >= 10) print (It is less) The “else” statement on the other hand is an alternate option. Ideally, the else statement much be written on the same line as the closing brace for the previous “if” block. R provides a vector version for the “if/else” statement. It is the “if/else” function. The following syntax is used to write the if/else function. ifelse(condition, x, y) This function returns vectors of various lengths and holds the longest argument. It contains the elements x[i] if condition [i] is TRUE, else y[i]. The arguments use vectors of various lengths. The “condition” argument is used to test, x is assessed as a “TRUE” value, and y is assessed a “FALSE” value. The following example is an “ifelse” function that displays 5 vectors. x <- 1:5 ifelse(x<5 | x>5, x, 0) [1] 1 2 4 4 0 The ifelse() function takes the first condition, and then takes the second condition if the first is TRUE and the third if the condition is FALSE. The condition can be a vector in this case. In this example, the results show a vector sequence of numbers from 1 to 5. All the values displayed are less than 5 and greater than 5.

วันศุกร์ที่ 31 มกราคม พ.ศ. 2563

สัญลักษณ์ และการกำหนดค่า สัญลักษณ์ใน R

สัญลักษณ์ และการกำหนดค่า  สัญลักษณ์ ของ R
Symbols and Assignments R Symbols


เมื่อเราสร้างตัวแปรใหม่ จะต้องมีชื่อที่ปกติแล้วจะอ้างถึงค่าหนึ่ง  ชื่อนั้นจริงแล้วคือสัญลักษณ์หนึ่ง ซึ่งหาค่าคืนกลับมาได้ สัญลักษณ์หนึ่งถือว่าเป็นออฟเจคของ R ด้วยอย่างหนึ่ง และสามารถนำไปจัดการแนวทางเดียวกับเป็นออฟเจค  สัญลักษณ์ที่อ้างถึงเป็น ออฟเจค R อย่างหนึ่งและเป็นชื่อของออฟเจค R หนึ่งเป็นสัญลักษณ์อย่างหนึ่ง
ตัวอย่างต่อไปนี้แสดงสัญลักษณ์ “x” และค่า “6” ที่ถูกกำหนดหรือเกี่ยวพันธ์กันสัญลักษณ์หรือตัวแปร
x <- 6
   x
  [1] 6

เรายังสารมารถใช้สัญลักษณ์เพื่อสร้างฟังก์่ชัน ในอีกทางหนึ่ง ฟังก์ชันสามารถที่จะกำหนดให้กับสัญลักษณ์ แต่ไม่จำเป็น สัญลักษณ์ในฟังก์ชันสามารถเป็นปิดหรือเปิด (bound or unbound).  มีสัญลักษณ์ 3 ชนิดภายในฟังก์ชัน ได้แก่ฟอมอลพารามีเตอร์ หรือฟอมอลอาร์กูเมนต์(formal parameters หรือ formal arguments) ตัวแปรโลคอล( local variable) และตัวแปรอิสระ(free variables)  ฟอมอลอาร์กูเมนต์ภายในฟังก์ชันหนึ่งเรียกว่าเป็นสัญลักษณ์ที่บาว(bound symbols) ที่มีอยู่ภายในตัวของฟังก์ชัน  สัญลักษณ์อื่นทั้งหมดในตัวของฟังก์ชั้นไม่เป็นโลคอลก็เป็นตัวแปรอันบาว   เนื่องจาก R เป็นภาษาแบบนิพจน์ ที่ตัวยกให้ผลต่างกับปกติ(case sensitive)  เราจำต้องระมัดระวังเมื่อใช้สัญลักษณ์ที่แตกต่างกัน  ดังเช่นชื่อตัวแปร  เราควรจะพิจารณาชนิดของระบบปฏิบัติการที่ใช้และประเทศที่เราอาศัยเมื่อใช้ชุดสัญลักษณ์ของR  ตามปกติสัญลักษณ์ตัวเลขอักขระ(alphanumeric) ดังเช่นจุด(periods (.)  และขีดล่าง(underscores (_)) สามารถนำมาใช้ได้  อย่างไรก็ตามยังมีข้อจำกัดอยู่บ้าง  ชื่อหนึ่งๆจะต้องเริ่มต้นด้วยจุด(period) หรือตัวอักษรตัวหนึ่ง ถ้าชื่อหนึ่งเริ่มด้วยจุดแล้วตัวอักขระตัวที่สองจะต้องไม่เป็นตัวเลข  เราสมารถมีชื่อที่ไม่จำกัดความยาว  ออฟเจคสามารถที่จะอ้างถึงได้ด้วยสัญลักษณ์ ซึ่งจริงแล้วป็นออฟเจค สัญลักษณ์หนึ่งๆ พิจารณาให้เป็นออฟเจคใน R.  สัญลักษณ์สามารถใช้ในทางเดียวกับออฟเจคอื่นๆและพิจารณาให้เป็นตัวแปรเช่นกัน

ในสิ่งแวดล้อม มีสัญลักษณ์คู่ชุดของค่า (set of symbol-value pairs) และ R มองหาสัญลักษณ์ภายในเฟรมของสิ่งแวดล้อม สัญลักษณ์ภายในสิ่งแวดล้อมประกอบด้วย รายการค้นหา ที่ค้นหาตามลำดับสำหรับสัญลักษณ์ที่ตรงกันกับคำค้น  ถ้าสัญลักษณ์นั้นถูกกำหนดตำแหน่งแล้วค่าให้มา  ดังนั้น ถ้าเรากำหนดสิ่งแวดล้อมเดียวกันให้กับสัญลักษณ์จำนวนมาก และเปลี่ยนไปค่าหนึ่งจากทั้งหมด สัญลักษณ์อื่นๆที่เหลือก็จะเปลี่อยนแปลงไปด้วย  เมื่อเราสร้างชื่อตัวแปรขึ้นมาตัวหนึ่ง  เราปกติแล้วเป็นการสร้างสัญลักษณ์ตัวหนึ่ง  ชื่อถือว่าเป็นสัญลักษณ์  ปกตแล้วชื่อนั้นจะมีค่าหนึ่ง ซึ่งเมื่อหารค่าจะได้ค่าคืนกลับมา  ในตัวอย่างต่อไปนี้ “x” มีค่า ”3”, ที่ซึ่ง “x” คือสัญลักษณ์ และ “3” เป็นค่าของสัญลักษณ์.  ค่านี้กำหนดให้กับสัญลักษณ์
> x <- 3

ค่าที่ถูกคืนกลับมาจากลูป “for”, “while”, และ “repeat” loops สามารถกำหนดผลลัพธ์ให้กับสัญลักษณ์ เช่นกันรายการของอาร์กูเมนต์หรือฟอมอลอากูเมนต์ในฟังก์ชันสามารถพิจารณาให้เป็นสัญลักษณ์  ในกรณีนี้ สัญลักษณ์กำหนดเป็นนิพจน์

R Assignments
การกำหนดค่าใน R ดำเนินการหาค่านิพจน์และผ่านค่าให้กับตัวแปร อย่างไรก็ตามผลลัพธ์ไม่ได้แสดงให้เห็นโดยอัตโนมัติ เราจำเป็นต้องเรียกใช้ชื่อตัวแปรเพื่อดูผลลัพธ์  ใน R การกระทำทั้งหลายที่ทำใน R เป็นผลมาจากการเรียกใช้ฟังก์ชัน  การเรียกใช้ฟังก์ชันคืนค่าหนึ่งและมักจะต้องการชื่อหนึ่งที่จะถูกกำหนดค่านั้นให้ มีอยู่สองแนวทางที่เราสามารถกำหนดค่าหนึ่งๆ  เราสามารถกำหนดค่าหนึ่งโดยใช้เครื่องหมายกำหนดค่า (assignment operator) ประ กอบด้วยเครื่องหมายน้อยกว่าและเครื่องหมายลบด้วยกัน(<-)  และเครื่องหมายเท่ากับ(=) เป็นเครื่องหมายกำหนดค่าใช้ในการกำหนดค่าให้กับชื่อตัวแปร  ตัวกระทำเท่ากับ = เป็นทางเลือกนอกจากเครื่องหมายกำหนดค่าน้อยกว่าและเครื่องหมายลบ  ตัวกระทำ <-  สามารถนำมาใช้ที่ใดๆใน R, แต่ตัวกระทำเครื่องหมาย = สามารถมาใช้ได้เฉพาะในนิพจน์ที่นำเข้าที่บรรทัดคำสั่งหรือในส่วนของนิพจน์ที่ใช้วงเล็บ  ตัวกระทำทั้งสองชี้ไปที่ออฟเจคที่รับค่าในนิพจน์ และที่ได้ถูกกำหนดให้สิ่งแวดล้อมที่ซึ่งนิพจน์ได้ถูกหาค่าไว้

 ต่อไปเป็นตัวอย่างหนึ่งที่เราสามารถสร้างการกำหนดค่าอย่างไรด้วยเครื่องหมายตัวกระทำกำหนดค่า (<-)
> squarey <- sqrt(x*x+2)

และต่อไปเราสร้างการกำหนดค่าอย่างไรด้วยเครื่องหมายเท่ากับ (=).
> squarey = sqrt(x*x+2)

ในทั้งสองกรณี ค่าของนิพจน์“sqrt(x*x+2)”  ถูกเก็บไว้ในชื่อตัวแปร“squarey”. เมื่อตัวแปร “squarey” สั่งให้ทำงาน ตัวแปรจะกลายเป็นออฟเจคภายในสิ่งแวดล้อม  ไม่จำเป็นต้องคำนึงถึงว่าสัญลักษณ์การกำหนดค่าใดที่เราใช้  ขึ้นอยู่ดับเรา บนฐานของความถนัดและชอบที่จะเลือกใช้อย่างหนึ่งอย่างใด  เพียงแต่จำไว้ว่า R นั้นให้ผลต่างกันกับตัวพิมพ์เล็กและใหญ่ ดังนั้นถ้าเราใช้ “squareY” , มันจะแตกต่างจาก“squarey”. ชื่อทั้งสองเหล่านี้แตกต่างกันตามการรับรู้ของ R. เราควรจะระวังว่า R จะไม่แสดงข่าวสารใดออกมาเมื่อเรากำหนดค่าให้ตัวแปร  เราไม่จำเป็นต้องนำเข้าชื่อของตัวแปรที่บรรทัดคำสั่งและกด

ตัวอย่างเช่น  ถ้าราต้องการแสดงผลลัพธ์  เราจำต้องทำดังต่อไปนี้:
squarey <- sqrt(1*2+2)
squarey
          [1] 2

หลังจากกำหนดค่าให้ตัวแปรแล้ว เราเรียกโดยอ้างถึงชื่อตัวแปรนั้นเพื่อแสดงค่าที่กำหนดให้ตัวแปรนั้น ประโยคคำสั่งการกำหนดค่าอาจรวมเอานิพจน์เดี่ยวโดยไม่มีฟังก์ชัน   ต่อไปเป็นตัวอย่างหนึ่งของการกำหนดค่าด้วยนิพจน์เดี่ยว
y <- 10 + 2

การกำหนดค่าสามารถทำได้อีกวิธี โดยการเปลี่ยนทิศทางของเครื่องหมายตัวกระทำจากน้อยกว่าและลบไปเป็น rs (<-) ไปเป็น เครื่องหมายลบและมากกว่า (->).  การกำหนดค่าด้วยตัวกระทำในอีกทิศทางอาจดูคล้ายกับประโยคคำสั่งต่อไปนี้
> 10 + 2 -> y

การกำหนดค่าทำการหาค่านิพจน์และส่งผ่านค่าไปให้ตัวแปร แต่ไม่จะเป็นต้องแสดงผลหรือพิพม์ออกมาให้เห็นโดยอัตโนมัติ 

ประโยคคำสั่งการกำหนดค่าด้วยฟังก์ชันสามารถที่จะมีจำนวนอาร์กูเมนต์เท่าใดก็ได้ ตัวอย่างต่อไปนี้แสดงประโยคคำสั่งกำหนดค่าที่มีหลายอาร์กูเมนต์ โดยแสดงฟังก์ชันw() ด้วยเลข 4 จำนวน
> x <- w(23, 3, 4, 1)

ตัวกระทำกำหนดค่า(<-) ในกรณีนี้สามารถแทนได้ด้วยเครื่องหมายการกระทำเท่ากับl (=) หรือการกำหนดค่าสามารถใช้ได้กับฟังก์ชันกำหนดค่า assign()  การทำเช่นนี้เป็นเหมือนกับประโยคคำสั่งกำหนดค่า ด้วยฟังก์ชัน  w()  ตัวอย่างต่อไปนี้แสดงให้เราเห็นการใช้ฟังก์ชัน assign() อย่างไร  นีเป็นวิธีการทางเหลือกหรือวิธีที่สมนัยเท่าเทียมกันกับฟังก์ชัน w()
> assign(“x”, f(23, 3, 4, 1))

ตัวกระทำกำหนดคค่าทางซ้ายมือ(<-) พิจรณาเป็นแลบลัดสั้นในการใช้ฟังก์ชัน assign()  ตามที่ได้เรียนรู้มาแล้ว ตัวกระทำกำหนดค่าสามารถใช้ในทิศทางตรงข้าม  ตัวอย่างเช่นแทนที่จะใช้ตัวกระทำกำหนดค่าทางซ้าย (<-),  เราสามารถใช้ตัวกระทำกำหนดค่าทางขวา  ตัวอย่างต่อไปนี้แสดงให้เราเห็นการใช้ตัวกระทำกำหนดค่าทางขวา(->) สำหรับฟังก์ชันw()
> w(23, 3, 4, 1) -> x

การกำหนดค่าด้วยฟังก์ชัน ตัวกระทำกำหนดค่า<<- และ->> ถูกนำมาใช้เพื่อสร้างการกำหนดค่าด้วยฟังก์ชันเท่านั้น  ยังคงมีการใช้สำหรับการค้นหาสำหรับนิยามที่เหมือนกันด้วยชื่อตัวแปรเดียวกันภายในสิงแวดล้อมพ่อแม่ (parent environment)  ถ้าพบตัวแปรและไม่ได้ถูกล็อกไว้ แล้วค่านั้นถูกกำหนดอีกครั้ง  ถ้าตัวแปรหาไม่พบการกำหนดค่าจะใช้สิ่งแวดล้อมแบบโกรบอล(global environment)   ในการใช้ตัวกระทำ<<-  เราคงจะพิมพ์คำสั่งดังตัวอย่างต่อไป
 y <<- mean(10 + 2)

สำหรับการใช้ตัวกระทำ ->>  เราคงจะพิพม์ตามตัวอย่างต่อไป:
mean(10 + 2) ->> y

หมายเหตุ:  การกำหนดค่าใดๆที่ได้กระทำภายในฟังก์ชันนั้นเป็นแบบโลคอลและชั่วคราว (temporary)  หมายความว่า จะสูญเสียค่าไปเมื่อผู้ใช้ออกจากฟังก์ชัน  ดังนั้นการกำหนดค่า Y <- sqrt(Y) จะไม่ส่งผลต่อค่าอาร์กูเมนต์เมื่อเรียกใช้ฟังก์ชัน.

การกำหนดค่า ซุปเปอร์ ซับเซ็ต และ คอมเพล็กซ์
Super, Subset and Complex Assignments 

ตัวกระทำกำหนดค่าซุปเปอร์ใช้ในการสร้างการกำหนดค่าแบบถาวรและโกรบอลภายในฟังก์ชัน  ตัวกระทำกำหนดค่าแบบซุปเปอร์ (<<-) หรือฟังก์ชัน  assign9 ถูกใช้ภายใต้สถานะการณ์นี้  เมื่อมาถึงการกำหนดค่าซับเซ็ต มีความซับซ้อนในกรณีเฉพาะ  ประโยคคำสั่งต่อไปนี้คือตัวอย่างของการกำหนดค่าแบบซับซ้อน(complex assignment
 x[1:4] <- 22:12

ผลลัพธ์จากประโยคคำสั่งคล้ายคลึงกับต่อไปนี้
    ‘*prm*‘ <- x
     x <- "[<-"(‘*prm*‘, 1:4, value=22:12)
     val(‘*prm*‘)

ในประโยคคำสั่งข้างบน เราจะเห็นว่า index ถูกแปลงไปเป็นnumeric index หนึ่ง และแล้วแทนที่ด้วย sequential numeric index. ตัวแปรที่ปรากฏ “*prm*” จะถูกเขียนับและลบออกไป แต่ชื่อตัวแปรจะต้องไม่ใช้ในโค๊ด เราไม่จำเป็นต้องใช้open bracket ([) ด้วยตัวกระทำทางซ้าย  เรายังสามารถเปลี่ยนตำแหน่งฟังก์ชันด้วยตัวกระทำกำหนดค่าทางซ้าย   อาร์กูเมนต์ตัวสุดท้ายด้วยฟังก์ชัน val() คือค่าที่จะถูกกำหนด  ตัวอย่างต่อไปนี้แสดงให้เราเห็นว่าใช้ฟังก์ชันในตำแหน่งใหม่อย่างไร
numbers(x) <- c("a","b")

ผลลัพธ์จากประโยคคำสั่งฟังก์ชันคล้ายคลึงกับต่อไปนี้
     ‘*prm*‘ <- x
      x <- "numbers<-"(‘*prm*‘, value=c("a","b"))
      val(‘*prm*‘)

 การกำหนดค่าแบบคอมเพล็กสามารถหาค่าย้อนกลับแบบเนสท์ (recursively with nesting) ต่อไปคือการกำหนดค่าแบบซับซ็อนที่ใช้การเนสท์(nesting):
numbers(x)[4] <- “Four”

ประโยคคำสั่งนี้คล้ายคลึงกับต่อไปนี้:
     ‘*prm*‘ <- x
     x <- "numbers<-"(‘*prm*‘, value="[<-"(numbers(‘*prm*‘), 4, value="Four"))
     val(‘*prm*‘)

เราสามารถใช้การกำหนดค่าซุปเปอร์แบบดับเบิลทางซ้าย(double left super assignment (<<-)) นอกจากที่เป็นการกำหนดค่าแบบเดี่ยวทางซ้ายเดี่ยว(single left single assignment (<-)) เพื่อสร้างการกำหนดค่าแบบคอมเพล็กซ์
numbers(x)[4] <<- “Four”

ประโยคคำสั่งนี้ตรงกันกับต่อไปนี้
     ‘*prm*‘ <<- get(x, envir=parent.env(), inherits=TRUE)
     numbers(‘*prm*‘)[4] <- "Four"
     x <<- ‘*prm*‘
     val(‘*prm*‘)

วันอังคารที่ 28 มกราคม พ.ศ. 2563

ไฟล์ใน R และการใช้งาน

 Files

 Reading Files with Functions 
     Read.table() function
     Variations of read.table()
      Read.csv() function
      Scan()function
Importing & Reading Files 
      Excel Files
      Minitab Files
      SPSS File
      Built-in datasets



ไฟล์ใน R

ไฟล์ใน R ปกติแล้วมีนามสกุลไฟล์ของชื่อไฟล์  ตัวอย่างเช่น ‘datafile.csv’ ส่วนขยายหรือนามสกุล‘.csv’ แม้ว่า R ไม่ได้รับรู้ถึงส่วนขยายนี้ แต่ก็ช่วยให้ผู้ใช้รู้ถึงความแตกต่าง บางนามสกุลไฟล์โดยพื้นฐานที่ใช้ในการโปรแกรม R รวมทั้ง ‘. rda’, ‘.r’, ‘.txt’, and ‘.csv’.

ต่อไปคือการอธิบายพอสังเขปของชนิดไฟล์ที่ใช้ใน R ต่างๆ กัน
  • ไฟล์นามสกุล .RDA  เหล่านี้คือออฟเจคของR ที่ถูกบันทึกไว้  ซึ่งได้แก่ไฟล์แนบไว้ และไฟล์ที่โหลด  โดยใช้ นามสกุลไฟล์เป็น .rda หรือ .RData   ไฟล์ที่มีนามสกุล .RData และ .rda ก็เป็นไฟล์แบบเดียวกัน 
  • ไฟล์นามสกุล .R  ไฟล์ที่ถูกสร้างขึ้นภายในเอดิเตอร์ของ R โดยใช้ฟังก์ชัน dump ที่รวมเอาคำสั่ง R  บางไฟล์ Rอาจจะมีนามสกุลไฟล์ .q , .
  • ไฟลนามสกุล .TXT  – มีเท็กซ์ไฟล์ที่ถูกใช้เพื่อเก็บชุดข้อมูล R ใช้ฟังก์ชัน read.table() และฟังก์ชันwrite.table()  R ใช้ read.table() สำหรับนำเข้าข้อมูล (data input) และ อ่านข้อมูลจากเท็กซ์ไฟล์  แล้วมีการสร้างดาต้าเฟรม(data frame)โดยอัตโนมัติภายใน  ฟังก์ชัน write.table() ในอีกทางหนึ่งถูกใช้ในการสร้างเท็กซ์ไฟล์ 
  •  ไฟล์นามสกุล .CSV – CSV หรือ Comma Separated Values  หรือใช้คอมม่าในการแยกค่าในไฟล์เป็นไฟล์ข้อมูลใช้กันทั่วไปแบบการนำเข้าข้อมูลโดยใช้ฟังก์ชัน read.csv()

ไฟล์แบบ .R ปกติแล้วเก็บข้อมูลปริมาณมาก หรือเป็นออฟเจ็คข้อมูลแทนที่จะเป็นแบบนำเข้าข้อมูลจากคีย์บอร์ด เราสามารถนำเข้าออฟเจคข้อมูลขนาดเล็กในคอนโซลของ R ได้ที่เครื่องหมายเตรียมพร้อมรับคำสั่ง แต่ดีที่สุดในการเก็บออฟเจอข้อมูลขนาดใหญ่ในไฟล์แบบ .rda, .r, .txt, .csv, และไฟล์ข้อมูลอื่นๆ  ที่สามารถนำมาใช้ได้ แล้วใช้ ฟังก์ชัน  read และ write ข้อมูลเข้าไปใน R

 การอ่านไฟล์ข้อมูลด้วยฟังก์ชัน (Reading files with Functions)

R อ่านออฟเจคข้อมูลขนาดใหญ่เป็นเหมือนค่ามาจากไฟล์ภายนอก  แม้ว่าสามารถนำเข้าข้อมูลเพียงจำนวนน้อยทางคีย์บอร์ดในการเขียนโปรแกรม R ครั้งหนึ่งๆ สิ่งแวดล้อมการโปรแกรมก็ไม่ยุ่งยาก และคงจะต้องใช้เวลานานมากในการนำเข้าข้อมูลปริมาณมาก ดังนั้นจึงดีกว่าที่จะขยายขอบเขตไฟล์นำเข้าข้อมูลโดยใช้ไฟล์เอดิเตอร์เพื่อให้สะดวกตามความต้องการของภาษา

ตัวแปรและชนิดอื่นของข้อมูลควรที่จะเก็บในดาต้าเฟรม และแล้วอ่านด้วยฟังก์ชัน read.table() หรือด้วยฟังก์ชันนำเข้าที่เก่ากว่าเรียกว่า scan()  ฟังก์ชัน read.table() ใช้กันทั่วไปในการอ่านข้อมูลในรูปของตารางแบบสี่เหลี่ยมผืนผ้า  แต่จะแนะนำให้ใช้ฟังก์ชัน scan() ในการอ่านข้อมูลเชิงตัวเลขเมทริกซ์ขนาดใหญ่มาก

ในตอนต่อไปนี้จะได้เรียนรู้มากขึ้นเกี่ยวกับ ฟังก์ชัน read.table() และวิธีการอย่างไรในการใช้ด้วยอาร์กูเมนต์ที่แตกต่างกันในการอ่านไฟล์ข้อมูลชนิดต่างๆกัน และยังมองหาวิธีการใช้อย่างไรของฟังก์ชัน scan() และ read csv() หากต้องการ

ฟังก์ชัน read.table()
ฟังก์ชัน read.table() ใช้ในการอ่านข้อมูลจากไฟล์ภายนอกเข้ามาใน R โดยสนับสนุนการใช้อาร์กูเมนต์หลายอย่าง  แต่ต้องการเพียงชื่อไฟล์เพื่ออ่านข้อมูลเข้ามาใน ฑ  โดยสามารถอ่านข้อมูลทั้งหมดจากไฟล์ภายนอกหนึ่งหรือสามารถระบุว่าชอบที่จะอ่านข้อมูลโดยใช้อาร์กูเมนต์อย่างไร  การอ่านไฟล์จากภายนอก จำเป็นต้องแน่ใจข้อมูลถูกนำมาแสดงในรูปแบบเฉพาะ  ในบรรทัดแรกของข้อมูลจะต้องมีชื่อของตัวแปรแต่ละตัวในแถว ด้านล่างแต่ละตัวแปร ควรแสดงค่างของแต่ละตัวแปร ถ้าค่าของตัวแปรนั้นละไว้  R จะคิดว่าเป็นความตั้งใจให้เป็นเช่นนั้น  ค่าตัวเลขในไฟล์ข้อมูลถูกอ่านเป็นตัวแปรจำนวน และไม่ใช่ตัวแปรจำนวน ทั้งนี้และทั้งนั้นยังสามารถที่จะเปลี่ยนได้ถ้าจำเป็น

ต่อไปเป็นตัวอย่างของไฟล์ข้อมูล โดยเรียกว่า "Inventory.data" ไฟล์นี้รวมเอาคอร์ลัมน์ ประกอบเป็นแถว ป้ายกำกับว่าตัวอย่าง 01  ไม่จำเป็นที่จะต้องมีแถวมีป้ายกำกับเป็นคอร์ลัมน์  แต่ทำได้โดยยอมให้ R ใช้แถวดีฟอลท์หรือปริยาย

ข้อมูลตามชื่อตัวแปร และแถวที่มีแถวที่ได้กำกับไว้ อาจคล้ายกับตัวอย่าง ต่อไปนี้                                                 
                   Price               Item                Code            Status               <--  นี้คือชื่อตัวแปร
01              20.00               Book               010A             Sold
02              1.00                 Pen                  9290              Order
03              .50                   Eraser              30Q1             Pending

เพื่อที่จะอ่านเนื้อหาทั้งหมดของไฟล์ข้อมูล “Inventory.data”  เราคงใช้ฟังก์ชัน read.table() เพื่ออ่าน data frame โดยตรงเข้าไปใน R โดยการใช้ประโยคคำสั่งต่อไปนี้
> InventoryStatus <- read.table(“Inventory.data”)

ถ้าเราเลือกที่จะละแถวที่มีคอลัมน์กำกับไว้จากไฟล์ข้อมูล เราคงจำเป็นต้องรวมเอาหัวของอาร์กูเมนต์ เมื่ออ่านข้อมูล นีเป็นเรื่องที่เราจะอ่านข้อมูลเข้ามาอย่างไรด้วยอาร์กูเมนต์หัวรายการ(header) และตัวที่ใช้แยกข้อมูล
 > InventoryStatus <- read.table(“Inventory.data”, header=TRUE, sep=””)

ทั้งประโยคคำสั่งที่กำหนดให้กับเนื้อหาของไฟล์ไปยังออฟเจคหนึ่ง  ข้อมูลที่อยู่ใน “ Inventory.data” ไฟล์ถูกกำหนดให้ “InventoryStatus” object. file is assigned to the “InventoryStatus” object.

จากนี้คือคำอธิบายของประโยคคำสั่ง InventoryStatus – นี้คือออฟเจคที่จะเก็นเนื้อหาของ “Inventory.data”.
read.table() – ฟังก์ชันread.table() ต้องการไฟล์ภายนอก ในกรณีนี้บรรจุไว้ด้วยไฟล์ “Inventory.data”

file. header=TRUE – นำมาใช้ถ้าไฟล์ไม่ได้บรรจุป้ายกำกับแถวใดๆ ไว้  แต่มีชื่อของตัวแปรในบรรทัดแรก  ตัวแปรดังกล่าวบ่งถึงไฟล์ที่มีหัวรายการ  เมื่อไฟล์ไม่มีคอร์ลัมน์สำหรับป้ายกำกับแถว แล้วป้ายกำกับแถวถูกกำหนดด้วย
   sep=”” – นี่คือตัวแยกฟิลด์ใช้สำหรับแยกไฟล์ออกจากไฟล์  คู่่ของเครื่องหมายคำพูดแทน whitespaces และสามารถมีช่องว่างหนึ่งหรือมากกว่าหนึ่งช่องว่าง, บรรทัด, แท็บ(tabs) หรือการเคาะคีย์รีเทิร์น  เราสามารถใช้แนวทางต่อไปนี้คือ

Space delimited data – ให้ใช้ sep=” “ สำหรับข้อมูลจำกัดช่องว่าง (space delimited data)
Tab delimited data –  ให้ใช้ sep=”\t”  สำหรับข้อมูลจำกัดแท็บ
New line delimited data – ให้ใช้“sep=”\n” สำหรับข้อมูลจำกัดบรรทัดใหม่(new line delimited data)
หมายเหตุ  ข้อมูลหรือเท็กซ์ที่ทำให้จำกัดคือรูปแบบไฟล์อย่างง่าย ที่แยกห่างกันด้วยอักขระที่ตายตัว  โดยเท็กช์ปกติแล้วเป็นแต่ละส่วน และอักขระที่ใช้จะเรียกว่าตัวจำกัด(delimiters)s.

Variations of read.table()   
ฟังก์ชันread.table() นำไปใช้ในหลายรูปแบบในการอ่านข้อมูลเข้ามาใน R จากกริดรูปสี่เหลี่ยมผืนผ้า.  อาร์กูเมนต์ต่างๆ ที่ใช้ภายในฟังก์ชันเพื่อจัดการชนิดต่างๆของข้อมูลที่แตกต่างกัน  ต่อไปนี้เป็นรายการของการใช้ฟังก์ชัน theread.table() ต่างๆ กัน
1.  Encoding – เข้ารหัสเมื่อไฟล์หนึ่งบรรจุไว้ด้วยตัวอักขระที่ไม่ใช่ ASCII  เราควรแน่ใจได้ว่าการอ่านได้อย่างถูกต้อง ถ้าเราอ่านไฟล์ Latin-1 ในตำแหน่ง UTF-8 เราคงจำเป็นต้องใช้ประโยคคำสั่งต่อไปนี้ โดยทำงานสำหรับสตริงLatin-1 แต่อาจจะทำงานไม่ได้สำหรับChinese/Russian/Greek และบริเวณที่คล้ายคลึง อาร์กูเมนต์สำหรับไฟล์เข้ารหัส ถูกใช้ในการกำหนดชนิดของไฟล์เหล่านี้ read.table(“Inventory.data", fileEncoding="latin1")
 2.  Header – อาร์กูเมนต์หัวรายการควรจะใช้เมื่อไฟล์นั้นมีเพียงชื่อตัวแปร เมื่อR รู้ว่าไม่มีป้ายกำกับแถว แล้วจะเซ็ต header = TRUE ถ้าเรามีไฟล์หนึ่งที่ไม่มีป้ายกำกับแถว เราสามารถอ่านข้อมูลด้วยสิ่งที่คล้ายคลึงกับประโยคคำสั่งต่อไปนี้ read.table(“Inventory.data”, header=TRUE, row.names=1)

3.    Separator – The default separators, sep =”” and sep =”\t”, is used to create white spaces in files. This is used to create spaces, tabs, or newlines. The type of separator used will determine the input based on the quote argument. The following statement uses the new line separator. This means the when the data is read into R, each value will be placed on a new line. InventoryStatus <- read.table(“Inventory.data”, header=TRUE, sep=”/n”)

4.    ค่าที่ขาดไป (Missing Values) – คิดได้ว่าโดยปริยาย สำหรับไฟล์ที่มีค่าที่ขาดหาย และใช้ ์์ ์NA เพื่อแทนค่าที่ขาดหายเหล่านั้น  ถ้ามีค่าจำนวนที่ขาดหายในคอร์ลัมน์   NaN, Inf, และ –สตริงอักขระ Inf นำออกมาแสดง  ในฟิลด์ที่ว่า หรือ ค่าที่ขาดหายอาจแสดงเหมือนดังต่อไปนี้
                   Price                        Item                         Code                             Status           

01              20.00                         Book                       010A                            Sold
02              1.00                           Pen                          NaN                             NA
03              .50                            Eraser                       30Q1                           Pending

5.    Unfilled lines – When a file is exported from a spreadsheet, there might be some empty fields with missing separators. To read these files, use set fill = TRUE. InventoryStatus <- read.table(“Inventory.data”, header=TRUE, fill=TRUE)

6.    White spaces – If there is a separator, leading, or a trailing whites spaces in a character field, you can strip the space with the strip.white = TRUE argument. InventoryStatus <- read.table(“Inventory.data”, header=TRUE, strip.white=TRUE)

7.    Blank lines – The read.table() function ignores empty lines by default, but you can change it by declaring blank.lines.skip=FALSE. This only works with fill=TRUE. InventoryStatus <- read.table(“Inventory.data”, header=TRUE, fill=TRUE, blank.lines.skip=FALSE)
 8.    Classes – Theread.table()by default reads the columns as character vectors and then choose a class for each variable in the file. It checks for integers, logical numbers, numeric values, and complex variables. If there are missing entries, then the variables are converted to a factor. The colClasses used in the following statement to convert the character vectors to factors in the “Inventory.data” file.
read.table("Inventory.data", header = TRUE, colClasses = classes)

9.    Comments – Theread.table() function by default uses the ‘#’ to create comments. When R sees the ‘#’ in a quoted string, it ignores the rest of the line. If there are white spaces with a comment, the comment is treated as a blank line. When there are no comments in the file, the comment.char=”” syntax is used like how it is used in the following statement.

read.table(“Inventory.data”, comment.char="#")

10. Escape and Backslash – Operating systems have different ways of using the backslash and escape keys in text files. However, Windows uses the backslash in path names. In R, the backslash is optional in data files.Whenread.table() uses allowEscapes, which is false by default, the backslashes are then interpreted as escapes quotes. Escape arguments are interpreted with control characters, such as \a, \b, \f, \n, and \r.

11. Convenience functions– Theread.csv()andread.delim()functions provide arguments to theread.table()function for tab delimited and CSV files that are exported from spreadsheets in English speaking locations. Read.csv() function Theread.csv() function is used to read a data file with the “comma separated values” (csv) format. CSV files contain values with numbers and letters separated with a comma. The first row of the file usually contains label names for differentiating the columns for the values. Here is an example of a CSV with some data. It contains three columns and three rows of data. The data file is called “products.csv”. The columns are labeled “Product”, “Price”, and “Quantity”. It is assumed that the rows have three products, “Book”, “Stationary”, and, “Toy”. Here is how the data file might look with the data. Product              Price                            Quantity
Book                            9.99                            2
Stationary              3.00                            6
Toy                            24.00                            3

To read the data file, you will need to use the “read.csv” command. The command must have at least one argument, but you can have three or more arguments. In the following example, the first argument is the name of the data file, the second argument the first row for the labels, and the third argument specifies that there is a comma between each line. Here is how you can read the data and assign it to the “inventoryinfo” variable with three arguments. > inventoryinfo <- read.csv(file="products.csv",head=TRUE,sep=",")

The variable “inventoryinfo” contains three columns with data. A name is assigned to each column. The column names are on the first line within the file. To access each column, use the “$” to differentiate the names of the columns. For example, if you would like to access the data in the “Price” column, you would use the following command: > inventoryinfo$Price

If you are not sure which column in the data file you would like to access use “names” command to list all the names of the columns in the data file. Here is an example of how you would use the “names” command: > names(inventoryinfo)

คำสั่ง “summary” สามารถนำมาใช้เพื่อเรียกข้อมูลจากไฟล์ข้อมูล CSV   เป็นการใช้หลังจากไฟล์ข้อมูลถูกกำหนดให้ตัวแปร  จากนี้จะเป็นการใช้คำสั้่ง‘summary’ อย่างไร.
> summary(inventoryinfo)

ถ้าไฟล์นั้นวางอยู่ในไดเรคตอรีเฉพาะ เราคงจำเป็นต้องระบุไดเรคทอรีและชื่อโฟนเดอร์ เพื่ออ่านไฟล์ ข้อตกลงในการตั้งชื่อสำหรับการอ่านไฟล์จากโฟนเดอร์และไดเรคเทอร์หาได้จากโฟนเดอร์ข้อความช่วยเหลือ เพื่อสำรวจดูรายการของทางเลือกสำหรับอ่านไฟล์ ให้ใช้คำสั่ง help(read.csv)

หมายเหตุ:  ถ้าเราใช้ระบบปฏิบัติการวินโดว์ เราคงจำเป็นต้องใช้เบคสแลซ 2 ครั้ง(“\\”) ในการจัดการไฟล์นั้น

ถ้าเราไม่สามารถหาไฟล์นั้นได้ เราอาจมองหาไปที่โฟลเดอร์หรือไดเรคทอรีที่ผิดพลาด ให้ใช้คำสั่ง dir() เพื่อระบุที่อยู่ไฟล์พร้อมกับแยกแยะไฟล์ ถ้าเราลืมซื่อไฟล์  คำสั่ง getwd() จะแสดงไดเรคทอรีที่เราทำงานอยู่ล่าสุดให้เห็น

ถ้าเรามีข้อมูลอยู่ในรูปสเปรดชีท เราสามารถแปลงไฟล์นั้นเป็นไฟล์CSV  โดยการขยัดแถวบนสุดของแถวในไฟล์สเปรดชีท และบันทึกไฟล์เป็นไฟล์“.csv”   เอ็กเซลยอมให้เราบันทึกสเปรดชีทเป็นไฟล็ CSV ได้   เพื่อให้เข้าใจได้ดีขึ้นว่า R เก็บข้อมูลได้อย่างไร ให้เปิดไฟล์ CSV ในเอ็กเซล  หลังจากที่เราแปลงสเปรดชีทเป็นไฟล์ CSVแล้ว เราสามารถอ่านข้อมูลไฟล์นี้ไปเป็นตัวแปรหนึ่งตามปกติ
ตัวอย่างเช่น  ถ้าเราแปลงไฟล์เอ็กเซลไฟล์หนึ่งเรียกว่า “datainventory.xls” ไปเป็น “datainventory.csv”, เราสามารถอ่านเข้าไปในตัวแปร “data” โดยใช้คำสั่งต่อไปนี้

 > data <- read.csv(file="datainventory.csv",header=TRUE,sep=",");

ตัวอย่างนี้สร้างตัวแปรใหม่่ชื่อ “data”. เมื่อเรานำเข้าข้อมูล “data” ที่เครื่องหมายเตรียมพร้อม  ข้อมูลทั้งหมดที่เก็บไว้ในตัวแปรจะแสดงให้เห็น
หมายเหตุ: R เก็บเส้นทางข้อมูบในหลายทางเมื่อเราใช้คำสั่ง “read.csv”  โดยการใช้ตัวแปร “data frame” ชนิดตัวแปรที่เก็บข้อมูลทั้งหมดในรูปแบบของ data frame format ด้วยการแยกคอร์ลัมน์  เพื่อตรวจสอบชนิดของตัวแปรที่เรามี ให้ใช้คำสั่งattributes           
 ต่อไปเราคงเป็นวิธีใช้คำสั่งอย่างไรเพื่อหาข้อมูลชนิดตัวแปร “data”
ตัวอย่างเช่น  จากนี้จะแสดงรายการต่างๆ ที่ R อธิบายตัวแปร
 > attributes (data)

Scan() function
ฟังก์ชัน scan() นำไปใช้อ่านชนิดต่างๆของข้อมูล หรือ ออฟเจคข้อมูล  ตัวอย่างเช่น เวคเตอร์ข้อมูล เราสามารถปรับคำสั่งให้อ่านข้อมูลเฉพาะ คำสั่งที่รอสำหรับการนำเข้าจากผู้ใช้และคืนกลับค่านำเข้าที่เครื่องหมายเตรียมพร้อม  เพื่อที่จะอ่านเวคเตอร์ข้อมูล 3 เวคเตอร์จากไฟล์ข้อมูล “datavectors.dat”,  เราคงต้องใช้คำสั่งต่อไปนี้โดยใช้ตัวแปร “datav”
ตัวอย่างเช่น
    > datav <- scan(“datavectors.dat”, list(“”,1,1))

อาร์กูเมนต์ตัวที่สอง list(“”,0,0) คือdummyตัวหนึ่ง หรือโครงสร้างที่ล้มเหลว(false structure) สำหรับสร้างเว็คเตอร์ 3 เวคเตอร์ที่จะถูกอ่านเข้ามาในตัวแปร “datav”  ส่วนโดยใช้คำสั่งต่อไปนี้:
    > datalabel <- datav[[1]]; x <- datav[[2]]; y <- datav[[3]]

ให้สังเกตว่าเวคเตอร์ทั้งสามถูกเก็บไว้ในตัวแปร “datalabel” ซึ่งจะถูกใช้ในการอ่านเข้ามาเป็นเวคเตอร์  นี่คือการที่จะเข้าไปจัดการเวคเตอร์อย่างไรด้วยฟังก์ชัน scan()
   > datav <- scan("datavectors.dat", list(id="", x=1, y=1))

เพื่อเข้าจัดการตัวแปรโดยแยกจากกัน, ให้ใช้เครื่องหมายหรือสัญลักษณ์ “$”
    > datalabel <- datav$id; x <- datav$x; y <- datav$y

Importing & Reading Files
There are various file formats that can be imported into R. Earlier we discussed reading CSV and XLS files into R. Here we will revisit these files, as well as other file formats. We will discuss importing file formats such as Minitab, SPSS, and TXT files. Excel Files Most of the time the data that you would like to import is in Excel format. Since most organizations use Excel files, you will need to understand how to use various methods for importing Excel data in R. These methods will import Excel data into R before you start using it. They have their advantages and disadvantages, but they all read data from an Excel spreadsheet and return the data in a data frame into R. Here is an overview of the some of the methods used to read data from an Excel spreadsheet into R. Save Excel files as Text – You can save Excel files into CSV format in an Excel spreadsheet or with an external tool that allow batch processing. You can then use the “read.table()” function to import the text format (that is CSV). > txt <- read.table(“textfile.csv”, header = TRUE) Copy and Paste Data from Excel– This is one of the easiest solution or method, but you will need to open the Excel file, select the data, and then copy with the copy and paste commands or with the copy and paste options available in Excel. You can use this method when you would like to get things done quickly. This requires the “read.table()” function. > txt <- read.table(“clipboard”) Excel ODBC driver– This method requires the installation of the Excel Open Database Connectivity (ODBC) driver. This method is not well recommended because it requires several lines of code to install the drive, connect with the Excel file, and read the file. This method is used with Microsoft Windows and 32-bit R. The following example shows how to establish a connection, get the data sheet, and close the connection to the Excel file. First, open a connection to the Excel file. > require(RODBC) > connFile <- odbcConnectExcel(“excelFile.xlsx”) #open a connection Second, display and read the data sheet. > sqlTables(connFile) $tableName, “Sheet1”) > txt <- sqlFetch(connFile,”Sheet1”) # display all data sheets > txt <- sqlQuery(connFile, “select * from [Sheet1 $]”) # read data sheet Third, close the connection to the file. > close(connFile) # close the connection gdata package The gdata package is a cross platform solution that works on Windows, Mac OS, and Linux operating systems. The gdata package requires that you install Perl libraries, which should already be available on Linux and Max systems. However, it may require additional steps for Windows platforms. > require(gdata) > txt <- read.xls(“excelFile.xlsx”, datasheet = 1, header = TRUE) xlsReadWrite package The xlsReadWrite package does not support xlsx files and it is not widely use these days, but it is a method that can used. It requires the use of third party code from GitHub and CRAN and only works on Windows platforms. > require(xlsReadWrite) > xls.getshlib() > txt <- read.xls(“excelFile.xlsx”, datasheet = 1) XLConnect package The XLConnect package that is a Java based solution that works across most platforms. This works best with small data sets. If you are working with large data sets, it may take a long time. > require(XLConnect) > xlsFile <- loadWorkbook(“excelFile.xlsx”) > txt <- readWroksheet(xlsFile, datasheet = “Sheet1”, header = TRUE) It is preferable to import Excel files as CSV files using the “read.table()” function mentioned in (1) and in the “Reading Files with Functions”section. It is the easiest way to import xlsx files into R. However, if you have small data sets, you can use the XLConnect method. Minitab Files Minitab files contain data stored as the Minitab Portable Worksheet format. It uses the “read.mtp” file to read the xlsx file. The file returns a list with one component for each column, matrix, or constant that is stored in the Minitab worksheet. The process requires that you first load the “foreign” package, call the “read.mtp” function, and then read in the “.mtp” file. First, load the “foreign” package. > library(foreign) Second, call the “read.mtp” file. > help(read.mtp) Third, read the “.mtp” file. > myfile <- read.mtp(“myfile.mtp”) SPSS File An SPSS file or Statistical Package for the Social Sciences is a file format used to store data for statistical analysis. The file is stored with the “.sav” extension. SPSS files are data files that are opened with the “read.spps” function from the “foreign” package. The “to.data.frame” argument is used inside the function to determine if a data frame will be returned. The following process shows how to load, access, and read spss files. First, load the “foreign” package. > library(foreign) Second, access the “read.spss function. > help(read.spss) Third, read the “.sav” file. myfile <- read.spss(“dataFile.sav”, to.data.frame=TRUE)

Built-in datasets 
มี ชุดข้อมูล(datasets)มากกว่า 100 ชุดตามรายการใน แพคเกจ“datasets”   เพื่อเข้าไปดูรายการชุดข้อมูล ให้ใช้คำสั่ง data()” ที่เครื่องหมายเตรียมพร้อม  ก็จะแสดงรายการชุดข้อมูลตามชื่อตามลำดับตัวอักษร พร้อมกันนั้นยังโหลดชุดข้อมูลเข้าไปในหน่วยความจำสำหรับการวิเคราะห์ทางสถิติ
ตัวอย่างเช่น ถ้าเราต้องการโหลดชุดข้อมูล “infert” เข้าสู่หน่วยความจำ  เราควรนำเข้าที่เตรียมพร้อมรับคำสั่งดังนี้
 > data(infert)

วันอาทิตย์ที่ 26 มกราคม พ.ศ. 2563

บทนำ R

บทนำIntroduction 

การโปรแกรม R คืออะไร What is R Programming?

ประวัติและภูมิหลังของR History and Background of R

ใช้ R ทำอะไรบ้าง What is R used for?

เริ่มต้นการใช้ R Getting Started with R:

ติดตั้ง เริ่มต้นใช้ และเลิกใช้ R Installing, Starting and Stopping R

การดำเนินการไฟล์และรูปแบบไฟล์ File Operations and File Formats

การเขียนโค็ดคำสั่งและเท็กซ์เอดิเตอร์ Writing Code and Text Editors

การโค๊ดคำสั่งใน R Writing R Code

เท็กซ์เอดิเตอร์ของ R  R Text Editors

ไวยากรณ์พื้นฐานของ R Basic R Syntax


การโปรแกรม R คืออะไร
    R คือซอพท์แวร์โปรแกรมฟรีใช้สำหรับการโปรแกรมทางสถิติและงานกราฟิกส์  นักสถิติ นักวิทยาศาสตร์ นักวิเคราะห์ นักทำเหมืองข้อมูล(data miners) และนักคณิตศาสตร์ ใช้การเขียนโปรแกรมด้วย R เพื่อการคำนวณ ทำประชามติ (conduct polls) และการสำรวจ  เป็นซอพท์แวร์ที่มีความสามารถสูง และมีภาษาที่สามารถขยายความสามารถได้ด้วยสภาพแวดล้อมที่สามารถโปรแกรมได้ โดยการเขียนสคริปซ์ที่บรรทัดคำสั่ง (command-line) สูตรต่างๆ ในรูปกระดาษทดคำนวณ  ทำให้ช่วยในการแยกสกัดข้อมูลทางสถิติสำคัญออกจากชุดข้อมูลและแยกออกจากกรฟิกส์ แล้วทำให้ง่ายต่อการวิเคราะห์  R ได้รับการพิจารณาให้เป็นเครื่องมือในการวิเคราะห์ข้อมูล เป็นภาษาการโปรแกรม เป็นตัววิเคราะห์ทางสถิติและเป็นซอพท์แวร์แบบเปิด(open source software) และยังเป็นการประยุกต์เสริมร่วมมือกันสำหรับนักวิทยาศาสตร์สถิติและนักวิทยาศาสตร์คอมพิวเตอร์

ต่อไป เป็นการอธิบายว่าการโปรแกรม R จัดประเภทกลุ่มอย่างไร
เครื่องมือการวิเคราะห์ข้อมมูล Data Analysis Tool – เป็นเครื่องมือที่ใช้สำหรับการวิเคราะห์ทางสถิติ
การ มองภาพข้อมูล (data visualization) และการสร้างโมเดลข้อมูล(data models).
ภาษาการโปรแกรม(Programming Language) – เป็นภาษาที่ใช้เขียนสคริปซ์และฟังก์ชัน  Objects, functions, และ operators นำมาใช้เพื่อประมวลผล สร้างข้อมูลและคำนวณข้อมูล. เพียงไม่กี่บรรทัดของรหัสคำั่งที่ใช้ในการคำนวณที่ซับซ้อน
ตัววิเคราะห์ทางสถิติ(Statistics Analyzer) – ฟังชันทั้งหลายนำมาใช้ประจำเพื่อสร้างกราฟิกส์และโมเดลข้อมูล และข้อมูล  วิธีการ(Methods)มีพร้อมให้ใช้ดำเนินการในการวิจัยทางสถิติและการการทำโมเดล(modeling)
ซอพท์แวร์แบบเปิด(Open Source Software) – ผู้ใช้สามารถดาวโหลดและใช้ภาษาที่ให้มาได้ฟรี รวมทั้งการใช้ซอร์สโค๊ดที่ปรับปรุงได้ฟรี หมายความว่าใครๆสามารถใช้วิธีการ และอัลกอริธึม กับระบบและการประยุกต์ใช้อื่นๆ
การประยุกต์ทางคณิตศาสตร์แบบร่วมมือ(Collaborative Mathematical Application) –  โดยอนุญาตให้นักคณิตศาสตร์ นักสถิติ และนักวิทยาศาสตร์คอมพิวเตอร์และอื่นๆร่วมมือกันเป็นเครือข่ายออนไลน์  ผู้ใช้จากชุดทักษะและภูมิหลัง ที่หลากหลาย สามารถร่วมมือช่วยเหลือกันและสื่อสารแลกเปลี่ยนข่าวสารกันและกันในโครงงานต่างๆ

ในชุดของRซอพท์แวร์  ที่บูรณาการด้วยลักษณะต่างๆ สำหรับการคำนวณ การดำเนินการข้อมูล(data manipulation) และแสดงผลเป็นกราฟิกส์

R ยังรวมเอาลักษณะต่างๆดังนี้
  • เครื่องมือที่ให้ผลดีสำหรับดำเนินการและการจัดเก็บข้อมูล(handling and storing data) 
  •  ให้ผลดีในการพัฒนาวิธีการ ที่ต้องการให้การวิเคราะห์ข้อมูลมีปฏิสัมพันธ์ 
  • ที่รวมของเครื่องมือในการวิเคราะห์ข้อมูล 
  • มีลักษณะทางกราฟิกส์สำหรับการวิเคราะห์และแสดงผลข้อมูลได้ทางกายภาพหรือโดยกายภาพ( computer or physically) 
  • มีลักษณะการโปรแกรมแบบ (S programming features), เช่น เงื่อนไข การกำหนดฟังก์ชันโดยผู้ใช้ และลูป. 
  • สนับสนุนเลขคณิตเมตริก(matrix arithmetic) และ การโปรแกรมแบบขั้นตอนวิธีการ(procedural programming) ด้วยการใช้ฟังก์ชัน 
  • ประกอบด้วยโครงสร้างข้อมูลที่รวมเอา เวคเตอร์ เมตริก อเรย์ ดาต้าเฟรม(dataframes) และลิสท์  (lists)
  • รวมเอา ออฟเจคซ์ ดังเช่น โมเดลรีเกรสชัน อนุกรมเวลา (time series) และ geo-spatial coordinates.
ในหนังสือนี้ ผู้อ่านจะได้เรียนรู้ลักษณะเหล่านี้มากขึ้นในตัวอย่างและการแสดงในรายละเอียด

ประวัติและภูมิหลังของ R (History and background of R)
การโปรแกรมR ได้สร้างขึ้นโดย Ross Ihaka และ Robert Gentleman ที่มหาวิทยาลัย Auckland ประเทศ นิวซีแลน    ชื่อ R มาจากอักษรตัวแรกของชื่อผู้สร้าง คือ Ross และ Robert  โดยได้แนวการพัฒนามาจากภาษา การโปรแกรม S  ซึ่งยังคงอยู่ในการพัฒนาของทีมหลักเดียวกันในการพัฒนาภาษาโปรแกรม R ในประเทศนิวซีแลนด์  R ปกติแล้วเป็น โครงงาน GNU (GNUs Not Unix) ที่เขียนขึ้นด้วยภาษา C , Fortran และ R   โดย R มีให้ใช้ได้ฟรีภายใต้ไลเซนซ์ สาธารณะ (GNU General Public Licens) และมีให้ใช้ได้ในการรันบนระบบปฏิบัติการวินโดว์  Mac OS X  และระบบปฏิบัติการ Unix

ใช้ R ทำอะไรบ้าง
R ส่วนมากใช้สำหรับ วิชาสถิติและการทำโมเดลข้อมูล (data modeling)  แต่ยังใช้ในการสกัดข้อมูลจากกราฟิกส์เพื่อการวิเคราะห์  ประกอบด้วยแพคเกจซ์แนะนำและมีมาตรฐานที่ใช้สำหรับเก็บฟังก์ชันและชุด  R ใช้ลักษณะต่างๆ จากโปรแกรม S, อันเป็นระบบทางสถิติที่ใช้กันโดยทั่วไปโดยนักสถิติ โดย S ประมวลการวิเคราะห์ทางสถิติเป็นชุดโดยให้ผลลัพธ์เพียงครึ่งทางเท่านั้น (only halfway results) แต่ R จะให้ผลลัพธ์เอ้าพุทขั้นต่ำและเก็บผลลัพธ์ไว้เพื่อประเมินผลภายหลัง  แม้ว่า R ใช้บรรทัดคำสั่งในการนำเข้าสคริปซ์ แต่ยังสนับสนุนการใช้การเชื่อมต่อกับผู้ใช้แบบกราฟิกส์หลายอย่าง (GUIs) ในการจัดการกราฟิกส์และโมเดลข้อมูล  แนวทางที่ง่ายที่สุดในการใช้ผ่านทางเครือข่ายกราฟิกส์ ที่มีอยู่ในระบบวินโดว์ โดยสามารถสร้างสิ่งแวดล้อมแบบวินโดว์, OS X  หรือระบบยูนิกซ์

ตอนนี้ได้ให้ภูมิหลัง R พอสังเขป ต่อไปจะเริ่มต้นการใช้ R


เริ่มต้นใช้ R 
การติดตั้งโปรแกรม R (Installing R) 
เพื่อติดตั้ง R บนคอมพิวเตอร์ จำเป็นต้องดาวโหลดซอพท์แวร์ที่  http://www.r-project.org. หรือที่อื่นที่จัดให้
 1.ที่เว็บไซด์โปรเจค R คลิกที่ ลิงค์“CRAN” ภายใต้ชื่อหัวข้อ Download, Packages  จะเห็นรายการของ  CRAN mirror ไปทางขวา โดยเลือกลืงค์ CRAN Mirror ที่ใช้ได้ในอาณาบริเวณของผู้ใช้ แล้วเพจซ์เครือข่าย “Comprehensive R Archive Network” จะถูกเปิดขึ้น

2. ในหน้า “Comprehensive R Archive Network” ให้เลือกเวอร์ชั่นหนึ่งต่อไปนี้ แลัวทำตามแนวทางที่กำหนดเพื่อให้การติดตั้งสำเร็จ  ให้เลือกเวอร์ชั่นที่ประยุกต์ใช้ได้กับระบบปฏิบัติการเครื่องคอมพิวเตอร์. 1. Download R for Linux
2. Download R for Mac OS X
3. Download R for Windows

หมายเหตุ:  ถ้าติดตั้ง R บนระบบ Windows, ให้เลือก “base” package. สำหรับ Mac OS X, ให้เลือก package ที่ประยุกต์ใช้กับเวอร์ชั่นของระบบปฏิบัติการที่ใช้

เริ่มต้น และ เลิกใช้ R
ในการเริ่มใช้ R, ดับเบิลคลิกที่ไอคอนของโปรแกรม R บนเดสท็อป  คอนโซล R จะถูกเปิดออกมาโดยมีบางข้อความแนะนำ แนะนำให้อ่านข่าวสารนั้นเพื่อเรียนรู้มากขึ้นเกี่ยวกับ R  ตอนล่างของข่าวสารข้อความแนะนำ จะเห็นเครื่องหมายเตรียมพร้อมหรือเคอเซอร์ อันเป็นที่ซึ่งผู้ใช้สำหรับเขียนคำสั่ง โดยสามารถแก้ไขคำสั่งที่เพิ่งพิมพ์ไปโดยใช้ลูกศรทางซ้อยและขวา เมื่อต้องการปิดโปรแกรม R หรือเลิกใช้ให้พิมพ์  “q( )”.

ดำเนินการไฟล์และรูปแบบไฟล์ (File Operations and File Formats)
R ใช้ข้อมูลจากรูปแบบ .R, .txt, และไฟล์ .csv   ในการดึงข้อมูลเนื้อของรูปแบบไฟลฺ“filename.R”
ตัวอย่างเช่น
ผู้ใช้เขียนว่า“source(filename.R)” ที่บรรทัดคำสั่ง  เมื่อไฟล์ถูกดึงเข้ามา ระหัสคำสั่งที่มีอยู้ในไฟล์จะรันทำงานตำคำสั่งในไฟล์นั้น  คำสั่ง R เขียนด้วยเท็กซ์ธรรมดาและบันทึกเป็นไฟล์โดยใช้นามสกุล .R   จากนั้นสามารถที่จะรันรหัสคำสั่งจากบรรทัดคำสั่งหรือใน R instance.  ผู้ใช้ยังสามารถจัดการไฟล์จากภายนอกที่ไม่ได้อยู่้ในโฟนเดอร์ปัจจุบัน (current folder ) โดยการเขียนดังตัวอย่าง
 “source(R folder/filename.R)”  ที่บรรทัดคำสั่ง  เมื่อผู้ใช้จะสร้างไฟล์ชนิด R ให้ใช้ชื่อที่สื่อความหมาย ตัวอย่างเช่น “weekly_revenue.R”. ไฟล์ภายนอกนำมาใช้เพื่อเก็บออฟเจ็คข้อมูลขนาดใหญ่ ซึ่งจะถูกอ่านเข้ามาเป็นค่าข้อมูลต่างๆ ระหว่างเซสชันการทำงานของ R   ไฟล์อินพุทสามารถที่จะขยายปรับเปลี่ยนโดยใช้เครื่องมือ เช่น  text editors

การเขียนโค๊ดและเท็กเอดิเตอร์ 

การเขียน R โค๊ดให้ได้ดีจำต้องฝึกฝนและอาศัยการแนะนำจากสื่ออ้างอิง เช่นแนวทาง R สไตล์และนักเขียนโค๊ดมืออาชีพของกูเกิล  การเขียนโค๊ด R ที่ง่ายที่สุดโดยอาศัย R เท็กเอดิเตอร์ เช่น R Studio เพราะช่วยให้สามารถจัดการกับข้อมูลขนาดใหญ่  นักสถิติสามารถเข้าใช้โปรแกรมสำหรับดำเนินการข้อมูล รายงานทางสถิติ การวาดพล็อตกราฟและไดอะแกรมด้วยการคลิกไม่กี่คลิก

การเขียนโค๊ดคำสั่งใน R
สิ่งแรกผู้อ่านควรจะจำไว้เมื่อเขียนโค๊ด คือการใช้เครื่องหมายวรรคตอนอย่างเหมาะสม มีหลายวิธีใช้ใส่เครื่องหมายวรรคตอนกับโค๊ดที่เขียน  แต่ผู้เขียนโปรแกรมต้องทำอย่างคงเส้นคงวา  การทำเช่นนี้ช่วยให้ผู้อ่านอื่นๆเข้าใจสไตล์ของผู้เขียนโค๊ด  ต่อไปเป็นบางการชี้แนะสำหรับการเขียน R โค๊ดที่ดี

ชื่อไฟล์ – ชื่อไฟลควรจะจบด้วยนามสกุล R  ตัวอย่างเช่น “filename.r”  และไม่ต้องไม่ใช้อักษรพิมพ์ใหญ่โดยไม่จำเป็น เพราะว่าในบางระบบปฏิบัติการ แคสตัวพิมพ์ ใหญ่เล็ก มีความแตกต่างกัน  ไฟล์ที่จำเป็นต้องรันไปตามลำดับ โดยการใช้ตัวเลขนำหน้าในชื่อ ตัวอย่างเช่น:
   1_daily_revenue.R
   2_weekly_revenue.R
   3_monthly_revenue.R

ชื่อตัวแปรและชื่อฟังก์ชัน - ให้เขียนชื่อตัวแปรและฟังก์ชันด้วยตัวอักษรตัวพิมพ์เล็ก และใช้ขีดล่างในการแยกคำ ตัวอย่างเช่น  “room_rate”. ชื่อตัวแปรควรเป็นคำนาม และชื่อฟังก์ชันความเป็นกริยา ไม่ใช้ชื่อตามที่มีการกำหนดกันไว้แล้วทั้งที่เป็นตัวแปรและฟังก์ชัน  ผู้เขียนโปรแกรมไม่ต้องการที่จะทำให้ผู้อ่านสับสน
สเปสซ์  – สเปสซ์หรือช่องว่างวางไว้ระหว่างตัวดำเนินการหรือโอเปอร์เรเตอร์ (infix operators) (+, =, -), หลังเครื่องหมายคอมม่า ก่อนทางซ้ายวงเล็ป (นอกจากการเรียกใช้ฟังชัน (function calls) และใช้สเปสซ์หลังเครื่องหมายคอมม่าเสมอ  ถือว่ายังทำได้ที่วางสเปสซ์เพิ่มเติมระหว่างระหว่างการกำหนดค่า assignments (<-) และเครื่องหมายเท่ากับ (=) เพื่อทำให้โค๊ดที่เขียนขึ้นชัดเจนและสามารถอ่านได้ อย่าใช้สเปสซ์โดยรอบโค๊ดในวงเล็บ วงเล็บเหลี่ยม,:, ::, และ :::. ต่อไปเป็นตัวอย่างบางอย่างเมื่อใช้สเปสซ์และไม่ใช้สเปสซ์ 
   sum(1, 3, 5) – ไม่มีสเปสซ์หรือช่องว่าในการเรียกใช้ฟังก์ชัน นอกจากหลังคอมม่า
   23 + 5 - 4  -  สเปสซ์ระหว่างตัวดำเนินการ
              sum::get – ไม่มีสเปสซ์กับโคลอน(:) ดับเปิลโคลอน(::) หรือทริปเปิลโคลอน(:::).
              total = a + b + c –  สเปสซ์เพิ่มเติมเพื่อช่วยให้การอ่านง่ายขึ้น และการจัดวางที่ดูดี
              coordinates[5,1] – ไม่มีสเปสซ์โดยรอบโค๊ดในวงเล็บ.

วงเล็บปีกกา(Curly braces) – วงเล็บเปิดและวงเล็บปิด ควรจะบรรทัดของตัวเอง และต้องตามด้วยบรรทัดใหม่ ถ้าวงเล็บปิดตามด้วย else,  ซึ่งไม่จำเป็นต้องมีบรรทัดตัวเอง  โค๊ดที่อยู่ในวงเล็บต้องย่อหน้า ต่อไปเป็นตัวอย่าง  วิธีการเขียนโค๊ดกับวงเล็บ
.              if (x < 5 && sum)
              {   write("X is a Coordinate") }
              if (y == 0)
              {   get(y) } else { x > y }

Line statements – ผู้เขียนสามารถเขียนประโยคสั้นๆ ในบรรทัดเดียวกัน แต่พยายามจำกัดโค๊ดให้มีประมาณ 80อักขระต่อบรรทัด  if (x < 5 && sum) write("X is a Coordinate")

Indenting Code – ให้ใช้ 2 สเปสซ์ในการย่อหน้าโค๊ด และต้องไม่ใช้แท๊บ หรือผสมแท็บและสเปสซ์  อย่างไรก็ตาม ถ้าการนิยามฟังก์ชันใช้หลายบรรทัด แล้วให้ย่อหน้าในบรรทัดที่ 2   ตัวอย่างเช่น: calculate(x = "a + b",                           
                            y = "40 - 19",                           
                            z = "30 + 2 - 9")

Functions – ให้ใช้กริยาสำหรับชื่อฟังก์ชัน  ให้ใช้ฟังก์ชัน return() สำหรับการหลับตอนต้น และให้ใช้บรรทัดสูงสุด 20-30 ฟังก์ชันโดยประมาณบนจอภาพหนึ่ง

Comments – ให้คอมเมนต์แต่ละบรรทัดของโค๊ดของผู้เขียนด้วยเครื่องหมายคอมเมนต์ (#). ให้ใช้แดสซ์มากขึ้น(--) or (=)  เพื่อแบ่งไฟล์ของผู้เขียนโค๊ด ก็จะทำให้สามารถอ่านได้ง่าย  โดยที่ผู้เขียนโค๊ดสามารถวางคอมเมนต์ที่ใดก็ได้ในไฟล to

# Calculate weekly numbers ---------
# Plot coordinates ---------------
การเขียนโค๊ดได้อย่างถูกต้องนั้นได้มาจากการฝึกฝน  แต่สำหรับผู้เริ่มต้นใช่้ R สามารถจะปฏิบัติตามแนวทางที่แนะนำง่ายๆ ในการเริ่มต้น

การใช้เท็กเอดิเตอร์ 
จะทำให้ง่ายขึ้นมากในการเขียนโค๊ดแบบ GUI  (Graphical User Interface) เพราะว่าจะเขียนโค๊ดได้เร็วกว่าและง่ายกว่า  แม้ว่านักสถิติและนักวิทยาศาสตร์คอมพิวเตอร์ ชอบมากว่าที่จะเขียนที่บรรทัดคำสั่งของคอนโซล R  สำหรบคนที่ชอบมากกว่าที่จะเขียนโค๊ด R ในไฟล์ที่แยกออกไปต่างหาก ซึ่งจำเป็นต้องใช้เท็กเอดิเตอร์  เท็กซ์เอดิเตอร์ในระบบปฏิบัติการมักจะถูกนำมาใช้  แต่เอดิเตอร์เฉพาะจัดให้เพื่อบูรณากรกับการเขียนโปรแกรมR  รายการของเท็กเอดิเตอร์ของการเขียนโค๊ดโปรแกรม R
Tinn-R – เอดิเตอร์นี้ง่ายต่อการใช้ GUI text editor สำหรับการโปรแกรม R ในระบบวินโดว์
RKward – เท็กซ์เอดิเตอร์ R ที่ใช้งานง่าย ทำงานได้ดีกับสิ่งแวดล้อม GNU/Linux, Windows, และ Mac OS X  และขยายขอบเขตได้ใน IDE/GUI สำหรับ R.
RStudio – เอดิเตอร์นี้เป็นเครื่องมือที่ออกแบบอำนวยความสะดอกให้ผู้ใช้อย่างดี ที่คล้ายคลึงกับRKward, แต่งง่ายกว่าในการใช้งาน และยังใช้ได้ดีกับสิ่งแวดล้อมของระบบปฏิบัติการ Mac OS X, Windows, และ Linux
JGR – เอดิเตอร์นี้คล้ายกับ RStudio ด้วยความคล้ายคลึงกับ GUI ที่บูรณาการกับคอนโซลบรรทัดคำสั่ง ของ R
Emacs with ESS (“Emacs Speaks Statistics) – มีส่วนแพคเกจที่ทำงานร่วมกับสิ่งแวดล้อมแบบ Unix, Linux, Windows และ Mac OS X
มีเท็กซ์เอดิเตอร์หลายอย่างที่ผู้ใช้สามารถใช้ได้ในการเขียนโค๊ด R แต่เอดิเตอร์เหล่านี้ใช้โดยนักสถิติและนักวิทยาศาสตร์คอมพิวเตอร์

ไวยากรณ์พื้นฐานของ R   Basic R Syntax

R มีไวยากรณ์ที่ง่ายเป็นภาษาแบบนิพจน์อย่างหนึ่ง เป็นยูนิกแพคเกจที่มีcase sensitive ดังนั้น "A" ไม่เหมือนกับ"a" เมื่ออ้างถึงตัวแปร ไวยากรณ์ของสัญลักษณ์อาจเปลี่ยนฐานได้ตามประเทศและระบบปฏิบัติการ สัญลักษณ์เลขอักษร (alphanumeric)ทั้งหมดยอมให้มีได้ (เหล่านี้รวมทั้งตัวอักษรออกเสียงที่ใช้ในบางประเทศ) คำสั่งอย่างง่ายไม่เป็นนิพจน์ก็เป็นคำสั่งกำหนดค่า.
  1 + 1 –  นีคือนิพจน์.
  mean_average <- average(1, 5, 7, 19) – นี้คือการกำหนดค่า

คำสั่งจัดให้แยกกันด้วยเซมีโคลอนหรือบรรทัดคำสั่งใหม่  คำสั่งอย่างง่ายมักจัดกลุ่มด้วยวงเล็บปีกาเปิดและปิด      ({ }). เมื่อคำสั่งยังไม่สมบูรณ์ R จะใส่เครื่องหมายเตรียมพร้อมโดยดีฟอลท์

ต่อไปเป็นชนิดต่างๆกันของนิพจน์ที่ใช้ใน R
ตัวคงที่(Constants) – ตัวคงที่เป็นตัวเลขหรือเท็กซ์ใดๆ ในคอนโซลของ R  มีตัวคงที่อยู่ 5 ชนิดคือ จำนวนเต็ม, ตรรกะ, สตริง, จำนวนตัวเลข และจำนวนเชิงซ้อน   ต่อไปเป็นตัวอย่างของตัวคงที่สตริง
"R programming!"

ตัวดำเนินการเลขคณิต(Arithmetic operators) -  ตัวกระทำเลขคณิต ดังเช่น เครื่องหมายบวก (+), ตัวกระทำลบtion (-), ตัวดำเนินการหาร (/), ตัวดำเนินการคูณ (*), ตัวดำเนินการหารจำนวนเต็ม (%/%), หารหาเศษของจำนวนเต็ฒ(remainder for integer division) (%% modulo arithmetic) และ ตัวดำเนินการเอ็กโพเนนชิเอชัน(^) ต่างก็เป็นตัวดำเนินการที่ใช้ในการเขียนโปรแกรม R  ต่ำไปเป็นตัวอย่างตัวดำเนินการบวก
1 + 1

ตัวดำเนินการเปรียบเทียบและตรรกะ (Logical and Comparison operators) – ตัวดำเนินการทางตรรก เช่น  || (or) และ && (and) ใช้ในการเชื่อมค่าทางตรรก เพื่อให้ได้ผลทางตรรกะ หนึ่ง  ตรรก ! (not) คือค่าให้เป็นลบของค่าทางตรรก ตัวดำเนินการเปรียบเทียบ (<, >, <=, >=, ==, and !=) นำมาใช้เพื่อเปรียบเทียบค่าในเวคเตอร์เพื่อหาว่า เวคเตอร์หนึ่งใหญ่กว่า เล็กหว่า หรือ เท่่ากับอีกเวคเตอร์หรือไม่  ตัวดำเนินการ % ในตัวดำเนินการ% นำมาใช้เพื่อหาว่ามีการ match หรือไม่ระหว่างโอเปอร์แรนด์ทางซ้ายและขวา อันก่อให้เกิดเวคเตอร์ทางตรรก  ต่อไปเป็นตัวอย่าง การดำเนินการมากกว่า
a > 6

การเรียกใช้ฟังก์ชัน(Function calls) – การเรียกใช้ฟังก์ชันนั้นมีจำนวนใดๆเป็นอาร์กูเมนต์ด้วยชื่อเดียวกัน   ตัวอย่างเช่น functionName(argument1, argument2). ต่อไปเป็นตัวอย่างของการเรียกใช้ฟังก์ชัน: sqrt(7*3+3)

สัญลักษณ์และการกำหนดค่า(Symbols and assignments) – ถ้าไม่ใช่หลักตัวเลขหรือคีย์เวิรดเฉพาะแล้ว ก็จะเป็นสัญลักษณ์ ค่าต่างๆ สามารถกำหนดด้วยตัวกระทำ <-  ต่อไปเป็นตัวอย่างการกำหนดค่า ดังนี้: combineA <- c(3,5,7,9)

ลูป(Loops) - ลูปหนึ่งๆ ใช้สำหรับกำทำงานซ้ำของกลุ่มนิพจน์(expressions) สำหรับลูปที่ใช้รันนิพจน์สำหรับเป็นจำนวนครั้งเฉพาะ นิพจน์นั้นรันไปตามลำดับ ขณะที่ลูปทำงานจนกระทั่งเงื่อนไขไม่เป็นจริงหรือเท็จ และก่อให้เกิดค่าทางตรรก หนึ่ง  ต่อไปเป็นตัวอย่างสำหรับการทำงานลูปหนึ่ง
 for (x in 1:20)
{ sqr[x]^2 }

นิพจน์เงื่อนไข(Conditional expressions) – นิพจน์เงื่อนไขใช้ในการสร้างนิพจน์ที่ขึ้นอยู่กับกับเงื่อนไข เงื่อนไขควรสร้างค่าตรรกหนึ่ง และควรจะรันได้ถ้าเงื่อนไขเป็นจริง วงเล็บปีกกาอาจนำมาใช้หรือไม่ใช้ก็ได้   R ใช้ประโยคคำสั่ง if, else เพื่อเขียนนิพจน์เงื่อนไข ต่อไปเป็นตัวอย่างของนิพจน์เงื่อนไข
if( x < 0.07)
{ x <- x * 2
sqrt(x)}


โครงสร้างควบคุม ใน R

โครงสร้างควบคุม (Control Structures) โครงสร้างควบคุมใช้เพื่อควบคุมการไหลของประโยคคำสั่งที่ถูกสั่งให้ทำงานโดยตัวแปลของ R  โดยรวมประโยคคำสั...