15分钟入门R语言(附代码)

  • A+
所属分类:R语言
  1. # Comments start with number symbols.
  2. # You can't make multi-line comments,
  3. # but you can stack multiple comments like so.
  4. # in Windows you can use CTRL-ENTER to execute a line.
  5. # on Mac it is COMMAND-ENTER
  6. #############################################################################
  7. # Stuff you can do without understanding anything about programming
  8. #############################################################################
  9. # In this section, we show off some of the cool stuff you can do in
  10. # R without understanding anything about programming. Do not worry
  11. # about understanding everything the code does. Just enjoy!
  12. data()          # browse pre-loaded data sets
  13. data(rivers)    # get this one: "Lengths of Major North American Rivers"
  14. ls()            # notice that "rivers" now appears in the workspace
  15. head(rivers)    # peek at the data set
  16. # 735 320 325 392 524 450
  17. length(rivers)  # how many rivers were measured?
  18. # 141
  19. summary(rivers) # what are some summary statistics?
  20. #   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  21. #  135.0   310.0   425.0   591.2   680.0  3710.0
  22. # make a stem-and-leaf plot (a histogram-like data visualization)
  23. stem(rivers)
  24. #  The decimal point is 2 digit(s) to the right of the |
  25. #
  26. #   0 | 4
  27. #   2 | 011223334555566667778888899900001111223333344455555666688888999
  28. #   4 | 111222333445566779001233344567
  29. #   6 | 000112233578012234468
  30. #   8 | 045790018
  31. #  10 | 04507
  32. #  12 | 1471
  33. #  14 | 56
  34. #  16 | 7
  35. #  18 | 9
  36. #  20 |
  37. #  22 | 25
  38. #  24 | 3
  39. #  26 |
  40. #  28 |
  41. #  30 |
  42. #  32 |
  43. #  34 |
  44. #  36 | 1
  45. stem(log(rivers)) # Notice that the data are neither normal nor log-normal!
  46. # Take that, Bell curve fundamentalists.
  47. #  The decimal point is 1 digit(s) to the left of the |
  48. #
  49. #  48 | 1
  50. #  50 |
  51. #  52 | 15578
  52. #  54 | 44571222466689
  53. #  56 | 023334677000124455789
  54. #  58 | 00122366666999933445777
  55. #  60 | 122445567800133459
  56. #  62 | 112666799035
  57. #  64 | 00011334581257889
  58. #  66 | 003683579
  59. #  68 | 0019156
  60. #  70 | 079357
  61. #  72 | 89
  62. #  74 | 84
  63. #  76 | 56
  64. #  78 | 4
  65. #  80 |
  66. #  82 | 2
  67. # make a histogram:
  68. hist(rivers, col="#333333", border="white", breaks=25) # play around with these parameters
  69. hist(log(rivers), col="#333333", border="white", breaks=25) # you'll do more plotting later
  70. # Here's another neat data set that comes pre-loaded. R has tons of these.
  71. data(discoveries)
  72. plot(discoveries, col="#333333", lwd=3, xlab="Year",
  73.      main="Number of important discoveries per year")
  74. plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year",
  75.      main="Number of important discoveries per year")
  76. # Rather than leaving the default ordering (by year),
  77. # we could also sort to see what's typical:
  78. sort(discoveries)
  79. #  [1]  0  0  0  0  0  0  0  0  0  1  1  1  1  1  1  1  1  1  1  1  1  2  2  2  2
  80. # [26]  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  2  3  3  3
  81. # [51]  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  3  4  4  4  4  4  4  4  4
  82. # [76]  4  4  4  4  5  5  5  5  5  5  5  6  6  6  6  6  6  7  7  7  7  8  9 10 12
  83. stem(discoveries, scale=2)
  84. #
  85. #  The decimal point is at the |
  86. #
  87. #   0 | 000000000
  88. #   1 | 000000000000
  89. #   2 | 00000000000000000000000000
  90. #   3 | 00000000000000000000
  91. #   4 | 000000000000
  92. #   5 | 0000000
  93. #   6 | 000000
  94. #   7 | 0000
  95. #   8 | 0
  96. #   9 | 0
  97. #  10 | 0
  98. #  11 |
  99. #  12 | 0
  100. max(discoveries)
  101. # 12
  102. summary(discoveries)
  103. #   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  104. #    0.0     2.0     3.0     3.1     4.0    12.0
  105. # Roll a die a few times
  106. round(runif(7, min=.5, max=6.5))
  107. # 1 4 6 1 4 6 4
  108. # Your numbers will differ from mine unless we set the same random.seed(31337)
  109. # Draw from a standard Gaussian 9 times
  110. rnorm(9)
  111. # [1]  0.07528471  1.03499859  1.34809556 -0.82356087  0.61638975 -1.88757271
  112. # [7] -0.59975593  0.57629164  1.08455362
  113. ##################################################
  114. # Data types and basic arithmetic
  115. ##################################################
  116. # Now for the programming-oriented part of the tutorial.
  117. # In this section you will meet the important data types of R:
  118. # integers, numerics, characters, logicals, and factors.
  119. # There are others, but these are the bare minimum you need to
  120. # get started.
  121. # INTEGERS
  122. # Long-storage integers are written with L
  123. 5L # 5
  124. class(5L) # "integer"
  125. # (Try ?class for more information on the class() function.)
  126. # In R, every single value, like 5L, is considered a vector of length 1
  127. length(5L) # 1
  128. # You can have an integer vector with length > 1 too:
  129. c(4L, 5L, 8L, 3L) # 4 5 8 3
  130. length(c(4L, 5L, 8L, 3L)) # 4
  131. class(c(4L, 5L, 8L, 3L)) # "integer"
  132. # NUMERICS
  133. # A "numeric" is a double-precision floating-point number
  134. 5 # 5
  135. class(5) # "numeric"
  136. # Again, everything in R is a vector;
  137. # you can make a numeric vector with more than one element
  138. c(3,3,3,2,2,1) # 3 3 3 2 2 1
  139. # You can use scientific notation too
  140. 5e4 # 50000
  141. 6.02e23 # Avogadro's number
  142. 1.6e-35 # Planck length
  143. # You can also have infinitely large or small numbers
  144. class(Inf)  # "numeric"
  145. class(-Inf) # "numeric"
  146. # You might use "Inf", for example, in integrate(dnorm, 3, Inf);
  147. # this obviates Z-score tables.
  148. # BASIC ARITHMETIC
  149. # You can do arithmetic with numbers
  150. # Doing arithmetic on a mix of integers and numerics gives you another numeric
  151. 10L + 66L # 76      # integer plus integer gives integer
  152. 53.2 - 4  # 49.2    # numeric minus numeric gives numeric
  153. 2.0 * 2L  # 4       # numeric times integer gives numeric
  154. 3L / 4    # 0.75    # integer over numeric gives numeric
  155. 3 %% 2    # 1       # the remainder of two numerics is another numeric
  156. # Illegal arithmetic yeilds you a "not-a-number":
  157. 0 / 0 # NaN
  158. class(NaN) # "numeric"
  159. # You can do arithmetic on two vectors with length greater than 1,
  160. # so long as the larger vector's length is an integer multiple of the smaller
  161. c(1,2,3) + c(1,2,3) # 2 4 6
  162. # Since a single number is a vector of length one, scalars are applied 
  163. # elementwise to vectors
  164. (4 * c(1,2,3) - 2) / 2 # 1 3 5
  165. # Except for scalars, use caution when performing arithmetic on vectors with 
  166. # different lengths. Although it can be done, 
  167. c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6
  168. # Matching lengths is better practice and easier to read
  169. c(1,2,3,1,2,3) * c(1,2,1,2,1,2)
  170. # CHARACTERS
  171. # There's no difference between strings and characters in R
  172. "Horatio" # "Horatio"
  173. class("Horatio") # "character"
  174. class('H') # "character"
  175. # Those were both character vectors of length 1
  176. # Here is a longer one:
  177. c('alef', 'bet', 'gimmel', 'dalet', 'he')
  178. # =>
  179. # "alef"   "bet"    "gimmel" "dalet"  "he"
  180. length(c("Call","me","Ishmael")) # 3
  181. # You can do regex operations on character vectors:
  182. substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis "
  183. gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis."
  184. # R has several built-in character vectors:
  185. letters
  186. # =>
  187. #  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
  188. # [20] "t" "u" "v" "w" "x" "y" "z"
  189. month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
  190. # LOGICALS
  191. # In R, a "logical" is a boolean
  192. class(TRUE) # "logical"
  193. class(FALSE)    # "logical"
  194. # Their behavior is normal
  195. TRUE == TRUE    # TRUE
  196. TRUE == FALSE   # FALSE
  197. FALSE != FALSE  # FALSE
  198. FALSE != TRUE   # TRUE
  199. # Missing data (NA) is logical, too
  200. class(NA)   # "logical"
  201. # Use | and & for logic operations.
  202. # OR
  203. TRUE | FALSE    # TRUE
  204. # AND
  205. TRUE & FALSE    # FALSE
  206. # Applying | and & to vectors returns elementwise logic operations
  207. c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE
  208. c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE
  209. # You can test if x is TRUE
  210. isTRUE(TRUE)    # TRUE
  211. # Here we get a logical vector with many elements:
  212. c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE
  213. c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE
  214. # FACTORS
  215. # The factor class is for categorical data
  216. # Factors can be ordered (like childrens' grade levels) or unordered (like gender)
  217. factor(c("female""female""male", NA, "female"))
  218. #  female female male   <NA>   female
  219. # Levels: female male
  220. # The "levels" are the values the categorical data can take
  221. # Note that missing data does not enter the levels
  222. levels(factor(c("male""male""female", NA, "female"))) # "female" "male"
  223. # If a factor vector has length 1, its levels will have length 1, too
  224. length(factor("male")) # 1
  225. length(levels(factor("male"))) # 1
  226. # Factors are commonly seen in data frames, a data structure we will cover later
  227. data(infert) # "Infertility after Spontaneous and Induced Abortion"
  228. levels(infert$education) # "0-5yrs"  "6-11yrs" "12+ yrs"
  229. # NULL
  230. # "NULL" is a weird one; use it to "blank out" a vector
  231. class(NULL) # NULL
  232. parakeet = c("beak""feathers""wings""eyes")
  233. parakeet
  234. # =>
  235. # [1] "beak"     "feathers" "wings"    "eyes"
  236. parakeet <- NULL
  237. parakeet
  238. # =>
  239. # NULL
  240. # TYPE COERCION
  241. # Type-coercion is when you force a value to take on a different type
  242. as.character(c(6, 8)) # "6" "8"
  243. as.logical(c(1,0,1,1)) # TRUE FALSE  TRUE  TRUE
  244. # If you put elements of different types into a vector, weird coercions happen:
  245. c(TRUE, 4) # 1 4
  246. c("dog", TRUE, 4) # "dog"  "TRUE" "4"
  247. as.numeric("Bilbo")
  248. # =>
  249. # [1] NA
  250. # Warning message:
  251. # NAs introduced by coercion
  252. # Also note: those were just the basic data types
  253. # There are many more data types, such as for dates, time series, etc.
  254. ##################################################
  255. # Variables, loops, if/else
  256. ##################################################
  257. # A variable is like a box you store a value in for later use.
  258. # We call this "assigning" the value to the variable.
  259. # Having variables lets us write loops, functions, and if/else statements
  260. # VARIABLES
  261. # Lots of way to assign stuff:
  262. x = 5 # this is possible
  263. y <- "1" # this is preferred
  264. TRUE -> z # this works but is weird
  265. # LOOPS
  266. # We've got for loops
  267. for (i in 1:4) {
  268.   print(i)
  269. }
  270. # We've got while loops
  271. a <- 10
  272. while (a > 4) {
  273.     cat(a, "...", sep = "")
  274.     a <- a - 1
  275. }
  276. # Keep in mind that for and while loops run slowly in R
  277. # Operations on entire vectors (i.e. a whole row, a whole column)
  278. # or apply()-type functions (we'll discuss later) are preferred
  279. # IF/ELSE
  280. # Again, pretty standard
  281. if (4 > 3) {
  282.     print("4 is greater than 3")
  283. else {
  284.     print("4 is not greater than 3")
  285. }
  286. # =>
  287. # [1] "4 is greater than 3"
  288. # FUNCTIONS
  289. # Defined like so:
  290. jiggle <- function(x) {
  291.     x = x + rnorm(1, sd=.1) #add in a bit of (controlled) noise
  292.     return(x)
  293. }
  294. # Called like any other R function:
  295. jiggle(5)   # 5±ε. After set.seed(2716057), jiggle(5)==5.005043
  296. ###########################################################################
  297. # Data structures: Vectors, matrices, data frames, and arrays
  298. ###########################################################################
  299. # ONE-DIMENSIONAL
  300. # Let's start from the very beginning, and with something you already know: vectors.
  301. vec <- c(8, 9, 10, 11)
  302. vec #  8  9 10 11
  303. # We ask for specific elements by subsetting with square brackets
  304. # (Note that R starts counting from 1)
  305. vec[1]      # 8
  306. letters[18] # "r"
  307. LETTERS[13] # "M"
  308. month.name[9]   # "September"
  309. c(6, 8, 7, 5, 3, 0, 9)[3]   # 7
  310. # We can also search for the indices of specific components,
  311. which(vec %% 2 == 0)    # 1 3
  312. # grab just the first or last few entries in the vector,
  313. head(vec, 1)    # 8
  314. tail(vec, 2)    # 10 11
  315. # or figure out if a certain value is in the vector
  316. any(vec == 10) # TRUE
  317. # If an index "goes over" you'll get NA:
  318. vec[6]  # NA
  319. # You can find the length of your vector with length()
  320. length(vec) # 4
  321. # You can perform operations on entire vectors or subsets of vectors
  322. vec * 4 # 16 20 24 28
  323. vec[2:3] * 5    # 25 30
  324. any(vec[2:3] == 8) # FALSE
  325. # and R has many built-in functions to summarize vectors
  326. mean(vec)   # 9.5
  327. var(vec)    # 1.666667
  328. sd(vec)     # 1.290994
  329. max(vec)    # 11
  330. min(vec)    # 8
  331. sum(vec)    # 38
  332. # Some more nice built-ins:
  333. 5:15    # 5  6  7  8  9 10 11 12 13 14 15
  334. seq(from=0, to=31337, by=1337)
  335. # =>
  336. #  [1]     0  1337  2674  4011  5348  6685  8022  9359 10696 12033 13370 14707
  337. # [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751
  338. # TWO-DIMENSIONAL (ALL ONE CLASS)
  339. # You can make a matrix out of entries all of the same type like so:
  340. mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6))
  341. mat
  342. # =>
  343. #      [,1] [,2]
  344. # [1,]    1    4
  345. # [2,]    2    5
  346. # [3,]    3    6
  347. # Unlike a vector, the class of a matrix is "matrix", no matter what's in it
  348. class(mat) # => "matrix"
  349. # Ask for the first row
  350. mat[1,] # 1 4
  351. # Perform operation on the first column
  352. 3 * mat[,1] # 3 6 9
  353. # Ask for a specific cell
  354. mat[3,2]    # 6
  355. # Transpose the whole matrix
  356. t(mat)
  357. # =>
  358. #      [,1] [,2] [,3]
  359. # [1,]    1    2    3
  360. # [2,]    4    5    6
  361. # Matrix multiplication
  362. mat %*% t(mat)
  363. # =>
  364. #      [,1] [,2] [,3]
  365. # [1,]   17   22   27
  366. # [2,]   22   29   36
  367. # [3,]   27   36   45
  368. # cbind() sticks vectors together column-wise to make a matrix
  369. mat2 <- cbind(1:4, c("dog""cat""bird""dog"))
  370. mat2
  371. # =>
  372. #      [,1] [,2]
  373. # [1,] "1"  "dog"
  374. # [2,] "2"  "cat"
  375. # [3,] "3"  "bird"
  376. # [4,] "4"  "dog"
  377. class(mat2) # matrix
  378. # Again, note what happened!
  379. # Because matrices must contain entries all of the same class,
  380. # everything got converted to the character class
  381. c(class(mat2[,1]), class(mat2[,2]))
  382. # rbind() sticks vectors together row-wise to make a matrix
  383. mat3 <- rbind(c(1,2,4,5), c(6,7,0,4))
  384. mat3
  385. # =>
  386. #      [,1] [,2] [,3] [,4]
  387. # [1,]    1    2    4    5
  388. # [2,]    6    7    0    4
  389. # Ah, everything of the same class. No coercions. Much better.
  390. # TWO-DIMENSIONAL (DIFFERENT CLASSES)
  391. # For columns of different types, use a data frame
  392. # This data structure is so useful for statistical programming,
  393. # a version of it was added to Python in the package "pandas".
  394. students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"),
  395.                        c(3,2,2,1,0,-1),
  396.                        c("H""G""G""R""S""G"))
  397. names(students) <- c("name""year""house") # name the columns
  398. class(students) # "data.frame"
  399. students
  400. # =>
  401. #     name year house
  402. # 1 Cedric    3     H
  403. # 2   Fred    2     G
  404. # 3 George    2     G
  405. # 4    Cho    1     R
  406. # 5  Draco    0     S
  407. # 6  Ginny   -1     G
  408. class(students$year)    # "numeric"
  409. class(students[,3]) # "factor"
  410. # find the dimensions
  411. nrow(students)  # 6
  412. ncol(students)  # 3
  413. dim(students)   # 6 3
  414. # The data.frame() function converts character vectors to factor vectors
  415. # by default; turn this off by setting stringsAsFactors = FALSE when
  416. # you create the data.frame
  417. ?data.frame
  418. # There are many twisty ways to subset data frames, all subtly unalike
  419. students$year   # 3  2  2  1  0 -1
  420. students[,2]    # 3  2  2  1  0 -1
  421. students[,"year"]   # 3  2  2  1  0 -1
  422. # An augmented version of the data.frame structure is the data.table
  423. # If you're working with huge or panel data, or need to merge a few data
  424. # sets, data.table can be a good choice. Here's a whirlwind tour:
  425. install.packages("data.table") # download the package from CRAN
  426. require(data.table) # load it
  427. students <- as.data.table(students)
  428. students # note the slightly different print-out
  429. # =>
  430. #      name year house
  431. # 1: Cedric    3     H
  432. # 2:   Fred    2     G
  433. # 3: George    2     G
  434. # 4:    Cho    1     R
  435. # 5:  Draco    0     S
  436. # 6:  Ginny   -1     G
  437. students[name=="Ginny"] # get rows with name == "Ginny"
  438. # =>
  439. #     name year house
  440. # 1: Ginny   -1     G
  441. students[year==2] # get rows with year == 2
  442. # =>
  443. #      name year house
  444. # 1:   Fred    2     G
  445. # 2: George    2     G
  446. # data.table makes merging two data sets easy
  447. # let's make another data.table to merge with students
  448. founders <- data.table(house=c("G","H","R","S"),
  449.                        founder=c("Godric","Helga","Rowena","Salazar"))
  450. founders
  451. # =>
  452. #    house founder
  453. # 1:     G  Godric
  454. # 2:     H   Helga
  455. # 3:     R  Rowena
  456. # 4:     S Salazar
  457. setkey(students, house)
  458. setkey(founders, house)
  459. students <- founders[students] # merge the two data sets by matching "house"
  460. setnames(students, c("house","houseFounderName","studentName","year"))
  461. students[,order(c("name","year","house","houseFounderName")), with=F]
  462. # =>
  463. #    studentName year house houseFounderName
  464. # 1:        Fred    2     G           Godric
  465. # 2:      George    2     G           Godric
  466. # 3:       Ginny   -1     G           Godric
  467. # 4:      Cedric    3     H            Helga
  468. # 5:         Cho    1     R           Rowena
  469. # 6:       Draco    0     S          Salazar
  470. # data.table makes summary tables easy
  471. students[,sum(year),by=house]
  472. # =>
  473. #    house V1
  474. # 1:     G  3
  475. # 2:     H  3
  476. # 3:     R  1
  477. # 4:     S  0
  478. # To drop a column from a data.frame or data.table,
  479. # assign it the NULL value
  480. students$houseFounderName <- NULL
  481. students
  482. # =>
  483. #    studentName year house
  484. # 1:        Fred    2     G
  485. # 2:      George    2     G
  486. # 3:       Ginny   -1     G
  487. # 4:      Cedric    3     H
  488. # 5:         Cho    1     R
  489. # 6:       Draco    0     S
  490. # Drop a row by subsetting
  491. # Using data.table:
  492. students[studentName != "Draco"]
  493. # =>
  494. #    house studentName year
  495. # 1:     G        Fred    2
  496. # 2:     G      George    2
  497. # 3:     G       Ginny   -1
  498. # 4:     H      Cedric    3
  499. # 5:     R         Cho    1
  500. # Using data.frame:
  501. students <- as.data.frame(students)
  502. students[students$house != "G",]
  503. # =>
  504. #   house houseFounderName studentName year
  505. # 4     H            Helga      Cedric    3
  506. # 5     R           Rowena         Cho    1
  507. # 6     S          Salazar       Draco    0
  508. # MULTI-DIMENSIONAL (ALL ELEMENTS OF ONE TYPE)
  509. # Arrays creates n-dimensional tables
  510. # All elements must be of the same type
  511. # You can make a two-dimensional table (sort of like a matrix)
  512. array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4))
  513. # =>
  514. #      [,1] [,2] [,3] [,4]
  515. # [1,]    1    4    8    3
  516. # [2,]    2    5    9    6
  517. # You can use array to make three-dimensional matrices too
  518. array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2))
  519. # =>
  520. # , , 1
  521. #
  522. #      [,1] [,2]
  523. # [1,]    2    8
  524. # [2,]  300    9
  525. # [3,]    4    0
  526. #
  527. # , , 2
  528. #
  529. #      [,1] [,2]
  530. # [1,]    5   66
  531. # [2,]   60    7
  532. # [3,]    0  847
  533. # LISTS (MULTI-DIMENSIONAL, POSSIBLY RAGGED, OF DIFFERENT TYPES)
  534. # Finally, R has lists (of vectors)
  535. list1 <- list(time = 1:40)
  536. list1$price = c(rnorm(40,.5*list1$time,4)) # random
  537. list1
  538. # You can get items in the list like so
  539. list1$time # one way
  540. list1[["time"]] # another way
  541. list1[[1]] # yet another way
  542. # =>
  543. #  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
  544. # [34] 34 35 36 37 38 39 40
  545. # You can subset list items like any other vector
  546. list1$price[4]
  547. # Lists are not the most efficient data structure to work with in R;
  548. # unless you have a very good reason, you should stick to data.frames
  549. # Lists are often returned by functions that perform linear regressions
  550. ##################################################
  551. # The apply() family of functions
  552. ##################################################
  553. # Remember mat?
  554. mat
  555. # =>
  556. #      [,1] [,2]
  557. # [1,]    1    4
  558. # [2,]    2    5
  559. # [3,]    3    6
  560. # Use apply(X, MARGIN, FUN) to apply function FUN to a matrix X
  561. # over rows (MAR = 1) or columns (MAR = 2)
  562. # That is, R does FUN to each row (or column) of X, much faster than a
  563. # for or while loop would do
  564. apply(mat, MAR = 2, jiggle)
  565. # =>
  566. #      [,1] [,2]
  567. # [1,]    3   15
  568. # [2,]    7   19
  569. # [3,]   11   23
  570. # Other functions: ?lapply, ?sapply
  571. # Don't feel too intimidated; everyone agrees they are rather confusing
  572. # The plyr package aims to replace (and improve upon!) the *apply() family.
  573. install.packages("plyr")
  574. require(plyr)
  575. ?plyr
  576. #########################
  577. # Loading data
  578. #########################
  579. # "pets.csv" is a file on the internet
  580. # (but it could just as easily be be a file on your own computer)
  581. pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv")
  582. pets
  583. head(pets, 2) # first two rows
  584. tail(pets, 1) # last row
  585. # To save a data frame or matrix as a .csv file
  586. write.csv(pets, "pets2.csv") # to make a new .csv file
  587. # set working directory with setwd(), look it up with getwd()
  588. # Try ?read.csv and ?write.csv for more information
  589. #########################
  590. # Statistical Analysis
  591. #########################
  592. # Linear regression!
  593. linearModel <- lm(price  ~ time, data = list1)
  594. linearModel # outputs result of regression
  595. # =>
  596. # Call:
  597. # lm(formula = price ~ time, data = list1)
  598. # Coefficients:
  599. # (Intercept)         time  
  600. #      0.1453       0.4943  
  601. summary(linearModel) # more verbose output from the regression
  602. # =>
  603. # Call:
  604. # lm(formula = price ~ time, data = list1)
  605. #
  606. # Residuals:
  607. #     Min      1Q  Median      3Q     Max 
  608. # -8.3134 -3.0131 -0.3606  2.8016 10.3992 
  609. #
  610. # Coefficients:
  611. #             Estimate Std. Error t value Pr(>|t|)    
  612. # (Intercept)  0.14527    1.50084   0.097    0.923    
  613. # time         0.49435    0.06379   7.749 2.44e-09 ***
  614. # ---
  615. # Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
  616. #
  617. # Residual standard error: 4.657 on 38 degrees of freedom
  618. # Multiple R-squared:  0.6124,  Adjusted R-squared:  0.6022 
  619. # F-statistic: 60.05 on 1 and 38 DF,  p-value: 2.44e-09
  620. coef(linearModel) # extract estimated parameters
  621. # =>
  622. # (Intercept)        time 
  623. #   0.1452662   0.4943490 
  624. summary(linearModel)$coefficients # another way to extract results
  625. # =>
  626. #              Estimate Std. Error    t value     Pr(>|t|)
  627. # (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01
  628. # time        0.4943490 0.06379348 7.74920901 2.440008e-09
  629. summary(linearModel)$coefficients[,4] # the p-values
  630. # =>
  631. #  (Intercept)         time 
  632. # 9.234021e-01 2.440008e-09 
  633. # GENERAL LINEAR MODELS
  634. # Logistic regression
  635. set.seed(1)
  636. list1$success = rbinom(length(list1$time), 1, .5) # random binary
  637. glModel <- glm(success  ~ time, data = list1,
  638.     family=binomial(link="logit"))
  639. glModel # outputs result of logistic regression
  640. # =>
  641. # Call:  glm(formula = success ~ time, 
  642. #   family = binomial(link = "logit"), data = list1)
  643. #
  644. # Coefficients:
  645. # (Intercept)         time  
  646. #     0.17018     -0.01321  
  647. # Degrees of Freedom: 39 Total (i.e. Null);  38 Residual
  648. # Null Deviance:        55.35 
  649. # Residual Deviance: 55.12   AIC: 59.12
  650. summary(glModel) # more verbose output from the regression
  651. # =>
  652. # Call:
  653. # glm(formula = success ~ time, 
  654. #   family = binomial(link = "logit"), data = list1)
  655. # Deviance Residuals: 
  656. #    Min      1Q  Median      3Q     Max  
  657. # -1.245  -1.118  -1.035   1.202   1.327  
  658. # Coefficients:
  659. #             Estimate Std. Error z value Pr(>|z|)
  660. # (Intercept)  0.17018    0.64621   0.263    0.792
  661. # time        -0.01321    0.02757  -0.479    0.632
  662. # (Dispersion parameter for binomial family taken to be 1)
  663. #
  664. #     Null deviance: 55.352  on 39  degrees of freedom
  665. # Residual deviance: 55.121  on 38  degrees of freedom
  666. # AIC: 59.121
  667. # Number of Fisher Scoring iterations: 3
  668. #########################
  669. # Plots
  670. #########################
  671. # BUILT-IN PLOTTING FUNCTIONS
  672. # Scatterplots!
  673. plot(list1$time, list1$price, main = "fake data")
  674. # Plot regression line on existing plot
  675. abline(linearModel, col = "red")
  676. # Get a variety of nice diagnostics
  677. plot(linearModel)
  678. # Histograms!
  679. hist(rpois(n = 10000, lambda = 5), col = "thistle")
  680. # Barplots!
  681. barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow"))
  682. # GGPLOT2
  683. # But these are not even the prettiest of R's plots
  684. # Try the ggplot2 package for more and better graphics
  685. install.packages("ggplot2")
  686. require(ggplot2)
  687. ?ggplot2
  688. pp <- ggplot(students, aes(x=house))
  689. pp + geom_histogram()
  690. ll <- as.data.table(list1)
  691. pp <- ggplot(ll, aes(x=time,price))
  692. pp + geom_point()
  693. # ggplot2 has excellent documentation (available http://docs.ggplot2.org/current/)

下载 R

小额消费信贷用户数据
机器学习电子书
Excel数据可视化分析方法大全
误差分位数的默示有效估计与\ 自回归时间序列的预测区间

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: