R语言长宽数据转换

长数据如下图:

宽数据如下图:

library(magrittr)
library(tidyr)
library(reshape2)
#宽转长

    #gather方法
    test <- as.data.frame(ddd)
    test$year <- rownames(test)
    test1 <- gather(test,key="month",value="tempretaure",-year) %>%
    .[order(.$year),]
    write.table(test1,file="chang_data.txt",sep="\t",quote=F,col.names=T,row.names=F)

    #melt方法
    test2 <- melt(test,id.vars=c('year'),variable.name='month',value.name='tempretaure') %>% 
    .[order(.$year),]

#长转宽

    #spread方法
    kuan_data_1 <- spread(test2,month,tempretaure)

    #dcast方法
    kuan_data_2 <- dcast(test2,year~test2$month,value.var='tempretaure')
此条目发表在R分类目录。将固定链接加入收藏夹。

R语言长宽数据转换》有2条回应

  1. 说:

    你的这个长边宽的脚本感觉有点问题,不太全面

发表评论

电子邮件地址不会被公开。 必填项已用*标注

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Protected with IP Blacklist CloudIP Blacklist Cloud