简体   繁体   中英

lapply undoes my previous function, but I don't know why

I want to split a dataframe by the year column into a list of 33 different dataframes. Then I want to change it so that each year column in the list reads "2015". Then I want to write each dataframe to a file with files labeled by the name of the original year. I am very close to doing this:

hist<-read.csv("hist3.csv", skip = 9, header=TRUE)  #Read data

spt1<-split(hist, hist$year)                        #Split data

fun<-function(x){within(x, year<-2015)}             #Little function to change years

lapply(spt1, fun)                                   #Use the function on each dataframe 
                                                     #in list, looks good in console

   ###BUT here the year column changes from 2015 back to original years
lapply(names(spt1), function(x){write.table(spt1[[x]],    
   file = paste("met", x, ".met", sep = ""),append=T, 
   sep=paste(rep(" ",6), collapse=""), quote=F, row.names = FALSE,     
   col.names=FALSE)})

The .csv is here: hist3.csv

You could try by assigning the output to a new object ( spt2 ) or update the old object ( spt1 ) and then use write.table

 spt2 <- lapply(spt1, fun)
 lapply(names(spt2), function(x) {write.table(spt2[[x]], 
 file = paste("met", x, ".met", sep = ""),append=T, 
 sep=paste(rep(" ",6), collapse=""), quote=F, row.names = FALSE,     
 col.names=FALSE)})

 head(read.table('met1985.met', header=FALSE),3)
 #   V1 V2   V3   V4    V5   V6
 #1 2015  1 5.26 -1.5  -9.5 0.83
 #2 2015  2 5.30 -0.7  -9.2 0.00
 #3 2015  3 5.09 -0.5 -10.0 0.37

 head(read.table('met1996.met', header=FALSE),3)
 #    V1 V2   V3    V4     V5 V6
 #1 2015  1 1.87 -0.40  -6.69  0
 #2 2015  2 4.52 -0.94 -16.70  0
 #3 2015  3 6.93 -6.50 -10.47  0

Here is the outline of what I was thinking. Different approach. Next step would be to add a line to the loop to change each year to 2015.

    hist <- read.csv("C:/.../hist3.csv", header=TRUE,colClasses='character')
    spt1<-split(hist, hist$year)  
    names <- names(spt1)
    for (i in names){
    assign(paste("met",i,sep="."), hist[hist$year == i,])  
    }
    head(met.1985)


    year day radn maxt mint rain
     1 1985   1 5.26 -1.5 -9.5 0.83
     2 1985   2  5.3 -0.7 -9.2    0
     3 1985   3 5.09 -0.5  -10 0.37

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM