R中的小技巧

作者: 生信编程日常 | 来源:发表于2020-01-14 20:09 被阅读0次
    1. str()
      在很多语言里可以将其他类型转化为字符串,不过在R中会返回数据类型。
    data(iris)
    str(iris)
    

    返回:
    'data.frame': 100 obs. of 5 variables:
    $ Sepal.Length: num 7 6.4 6.9 5.5 6.5 5.7 6.3 4.9 6.6 5.2 ...
    $ Sepal.Width : num 3.2 3.2 3.1 2.3 2.8 2.8 3.3 2.4 2.9 2.7 ...
    $ Petal.Length: num 4.7 4.5 4.9 4 4.6 4.5 4.7 3.3 4.6 3.9 ...
    $ Petal.Width : num 1.4 1.5 1.5 1.3 1.5 1.3 1.6 1 1.3 1.4 ...
    $ Species : Factor w/ 2 levels "versicolor","virginica": 1 1 1 1 1 1 1 1 1 1 ...

    1. 通过链接读取数据
    site <- "http://random.org/integers/"  # 这是一个生成随机数的网站
    # 产生两列10行随机数,最小值100,最大值200
    query <- "num=10&min=100&max=200&col=2&base=10&format=plain&rnd=new"
    txt <- paste(site, query, sep="?") # 网址
    nums <- read.table(file=txt) # 读取
    
    1. 反引号
    df <- data.frame(x=rnorm(5),y=runif(5))
    names(df) <- 1:2
    

    取第一列,如果是这样则会报错:

    df$1
    

    报一个“错误: unexpected numeric constant in "df$1"”的错误。

    但是这样可以:

    df$`1`
    

    df$后tab键提示出来也是会有反引号的。

    做线性回归也可以:

    lm(`2`~`1`,data=df)
    
    1. 对数据框的操作

    新建数据:

    sales <- expand.grid(country = c('USA', 'UK', 'FR'),
                         product = c(1, 2, 3))
    sales$revenue <- rnorm(dim(sales)[1], mean=100, sd=10)
    
    

    transform增加列:

    usd2eur <- 1.5
    transform(sales, euro = revenue * usd2eur)
    
    1. cut / table
      cut可以把数据分成想要的区间:
    irisSL <- iris$Sepal.Length
    # 分成五个bins
    cut(irisSL, 5)
    # 也可以按我们想要的范围分割
    cut(irisSL, breaks = seq(1,8,1))
    

    可以用table统计每个范围的数目:

    table(cut(irisSL, 5))
    

    返回:
    (4.9,5.5] (5.5,6.1] (6.1,6.7] (6.7,7.3] (7.3,7.9]
    12 33 35 13 7

    欢迎关注~


    生信编程日常

    相关文章

      网友评论

        本文标题:R中的小技巧

        本文链接:https://www.haomeiwen.com/subject/imsaactx.html