rep的使用
rep(c(1,2,3),length.out=10) [1] 1 2 3 1 2 3 1 2 3 1 > rep(x = 1,... = 5) [1] 1 > rep(x = 1,each=10) [1] 1 1 1 1 1 1 1 1 1 1 > rep(c(1,2,3),each=10) [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 > rep(c(1,2,3),times=10) [1] 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
字符串(nchar和length,paste,substr,toupper,tolower,
> grep("[a-z]", letters) [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 > letters > grep("[b-c]", letters) [1] 2 3 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" "t" [21] "u" "v" "w" "x" "y" "z" > gsub("([ab])", "\\1_\\1_", "abc and ABC") [1] "a_a_b_b_c a_a_nd ABC" > grep("[a-b]", letters) [1] 1 2
grep,match,strsplite,outer)
nchar与length
> x <- c("one","first") > nchar(x) [1] 3 5 > length(x) [1] 2
paste
> month.abb [1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" > nth Error: object ‘nth‘ not found > paste(month.abb, x, sep = ": ", collapse = "; ") [1] "Jan: one; Feb: first; Mar: one; Apr: first; May: one; Jun: first; Jul: one; Aug: first; Sep: one; Oct: first; Nov: one; Dec: first" >
> substr(x,1,1) [1] "o" "f" > x [1] "one" "first" > substr(month.abb,1,2) [1] "Ja" "Fe" "Ma" "Ap" "Ma" "Ju" "Ju" "Au" "Se" "Oc" "No" "De" toupper(substr(month.abb,1,2)) [1] "JA" "FE" "MA" "AP" "MA" "JU" "JU" "AU" "SE" "OC" "NO" "DE" > tolower(substr(month.abb,1,2)) [1] "ja" "fe" "ma" "ap" "ma" "ju" "ju" "au" "se" "oc" "no" "de"
strsplit(x, "") [[1]] [1] "o" "n" "e" [[2]] [1] "f" "i" "r" "s" "t"
数据缺失的处理办法
> a <- c(na,1:49) Error: object ‘na‘ not found > a <- c(NA,1:49) > a [1] NA 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 [28] 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 > sum(a.na.rm) Error: object ‘a.na.rm‘ not found > sum(a.na.rm=TRUE) [1] 1 > sum(a,na.rm=TRUE) [1] 1225 > is.na(a) [1] TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [14] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [27] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE [40] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
outer
> y <- c(1:5) > outer(x,y,FUN ="paste") [,1] [,2] [,3] [,4] [,5] [1,] "one 1" "one 2" "one 3" "one 4" "one 5" [2,] "first 1" "first 2" "first 3" "first 4" "first 5" > x [1] "one" "first" > outer(y,x,FUN ="paste") [,1] [,2] [1,] "1 one" "1 first" [2,] "2 one" "2 first" [3,] "3 one" "3 first" [4,] "4 one" "4 first" [5,] "5 one" "5 first"
outer与paste的区别
> class(outer(y,x,FUN ="paste")) [1] "matrix" "array" > class(paste(month.abb, x, sep = ": ", collapse = "; ")) [1] "character"
原文:https://www.cnblogs.com/AlanNote/p/15139499.html