r - Modify columns in a dataframe by using function -
i'm trying modify data frame columns , positions. found solution want process in function data sets in directory , overwrite real data.
kw <- matrix(1:11400, ncol = 19) # make sample data kw <- kw[, !(colnames(kw) %in% c("v18","v19"))] # remove last 2 cols add <- c(kw$v18 <- 0,kw$v19<- 0) # add new columns 0 values kw$v1 <- kw$v1 * 1000 # modify first col of data frame kw <- kw[ ,c(1,18:19,2:17)] # replace col positions
lets have data set in directory
kw<-read.table("5lstt-test10.avgm", header = false,fill=false) # example shows how read single data `5lstt-test10.avgm` . . . . 5lstt-test10.avgm`
how can apply column modification process each data separately , overwrite or make new data?
edit output readlines("5lstt-test10.avgm", n = 1) can see 19 columns , think data has 600 rows
[1] " 9.0000e-02 0.0000e+00 2.3075e-03 -6.4467e-03 9.9866e-01 9.8648e-02 4.5981e-02 9.8004e-01 1.2359e-01 6.1175e-02 9.7701e-01 8.6662e-02 3.0034e-02 9.7884e-01 7.0891e-02 8.2247e-03 9.8564e-01 -8.7967e-11 4.3105e-02"
this way
read files , store in list this
# list down files in directory files.new = list.files(directory.path, recursive = true, pattern=".avgm") # read files , store in list file.contents = lapply(paste(directory.path,files.new, sep="/"), read.table, sep='\t', header = true)
next can modifications each of dataset in list this
outlist = lapply(file.contents, function(x){ # modifications kw <- x[, !(colnames(x) %in% c("v18","v19"))] add <- c(kw$v18 <- 0,kw$v19<- 0) kw$v1 <- kw$v1 * 1000 kw <- kw[ ,c(1,18:19,2:17)] })
and write modified data new files using function below
# function write files list object write.files = function(modified.list, path){ outlist = file.contents[sapply(modified.list, function(x) length(x) > 1)] sapply(names(outlist), function(x) write.table( outlist[[x]], file= paste(path, x, sep="/"), sep="\t", row.names=false)) }
writing data files
write.files(outlist, "/directory/path")
Comments
Post a Comment