-2

I have a csv file of dimension 26299*150, where the first row is blank. While exporting each column as text file the first blank row gets saved as '0' in the text file. I want it to be saved as a blank line in the first line of text file. Please help me with this.

sample = csvread("tn_filled.csv");
len = size(sample,2);
folder = 'D:\TMP';
for jj = 1 : len
    ffs = fullfile(folder,sprintf('tn%02d.txt',jj));
    fid = fopen( ffs, 'w');
    fprintf(fid,'%.2f\n',sample(:,jj));
    fclose(fid);
end
ssd007
  • 13
  • 2

2 Answers2

1
# first I create an example with 3 data sets and write them to disk. 
setwd("H:\\SO")
dir()
library(tidyverse)
unique(mtcars$gear)

a <- mtcars %>% 
  split(.$gear)

my_names <- c("tre", "fire", "fem")

names(a) <- my_names

for(i in 1:length(my_names)){
write_csv(a[[i]] , paste0(my_names[[i]], ".csv"))
}

rm(list = ls())

# Now I want to read in all the files. 
my_names <- c("tre", "fire", "fem")
files <- dir()

# I read in all the files
b <- map(files, read_csv) 

# I only select the column that I want
for(i in 1:length(files)){
 b[[i]] <- b[[i]]["gear"]   
} 

final_df <- do.call(dplyr::bind_rows, b)
final_df

# A tibble: 32 x 1
    gear
   <dbl>
 1     5
 2     5
 3     5
 4     5
 5     5
 6     4
 7     4
 8     4
 9     4
10     4
# ... with 22 more rows

I have not subsetted the column based on other columns, but it is easy to do...

xhr489
  • 1,957
  • 13
  • 39
0

Here's an approach that uses base R. First we need to create some data that resembles your description:

# Create dummy data - three files with 5 observations in each
set.seed(2)
dta <- data.frame(lat=sample(4, 15, replace=TRUE),
   lon=sample(4, 15, replace=TRUE), sm=sample(100, 15))
write.csv(dta[1:5, ], file="file01.csv", row.names=FALSE)
write.csv(dta[6:10, ], file="file02.csv", row.names=FALSE)
write.csv(dta[11:15, ], file="file03.csv", row.names=FALSE)

Now we read the files into a list, convert the list to a data frame, and extract the sm values matching a criterion:

# Read files and extract values
fls <- paste0("file0", 1:3, ".csv")
fls.lst <- lapply(fls, read.csv)
names(fls.lst) <- fls
all <- do.call(rbind, fls.lst)
vals <- all[all$lat==1 & all$lon==3, ]
write.csv(vals, file="sm_values.csv")
read.csv("sm_values.csv")
#              X lat lon sm
# 1 file01.csv.1   1   3 43
# 2 file02.csv.2   1   3  6
# 3 file02.csv.3   1   3 83

You should read the manual pages for each of these functions to see what they are doing.

dcarlson
  • 10,936
  • 2
  • 15
  • 18