R语言中的语句

一些函数不知道什么意思要查,看数值例子,做笔记,知道函数的功能,函数和返回值。

网页上查找关键词,巧用查找(ctrl+F)

R语言 sub与gsub函数的区别

> text <- c("we are the world", "we are the children")

> sub("w", "W", text)

[1] "We are the world"    "We are the children"

> sub("W","w",text)

[1] "we are the world"    "we are the children"

> gsub("W","w",text)

[1] "we are the world"    "we are the children"

> gsub("w","W",text)

[1] "We are the World"    "We are the children"

 

> sub(" ", "", "abc def ghi")

[1] "abcdef ghi"

> ## [1] "abcdef ghi"

> gsub(" ", "", "abc def ghi")

[1] "abcdefghi"

> ## [1] "abcdefghi"

从上面的输出结果可以看出,sub()和gsub()的区别在于,前者只替换第一次匹配的字符串,而后者会替换掉所有匹配的字符串。


R子集subset

> x<-c(6,1,2,3,NA,12)

> x[x>5]    #x[5]是未知的,因此其值是否大于5也是未知的

[1]  6 NA 12

> subset(x,x>5)  #subset直接会把NA移除

[1]  6 12

> subset(airquality, Temp > 80, select = c(Ozone, Temp))

    Ozone Temp

29     45   81

35     NA   84

36     NA   85

38     29   82

39     NA   87

40     71   90

...

> subset(airquality, Day == 1, select = -Temp)

    Ozone Solar.R Wind Month Day

1      41     190  7.4     5   1

32     NA     286  8.6     6   1

62    135     269  4.1     7   1

93     39      83  6.9     8   1

124    96     167  6.9     9   1

...

> subset(airquality, select = Ozone:Wind)

    Ozone Solar.R Wind

1      41     190  7.4

2      36     118  8.0

3      12     149 12.6

4      18     313 11.5

5      NA      NA 14.3


就是把x中所有不是NA的值赋予x,比如说x=c(1,2,NA,4),那么运行这个程序
x<-x[!is.na(x)]
以后,x=c(1,2,4)


猜你喜欢

转载自www.cnblogs.com/mohuishou-love/p/10231839.html