I am newbie in R. I got a problem when combining data, hope that someone help to resolve it. Suppose that I have two CSV files such as A.csv and B.csv are located at the path "C:\Users\Public\A". They look like that:
A.csv
T,2015,2016,2017,2018
X1,1,2,3,2
X2,1,2,2,3
X3,1,3,4,2
B.csv
T,2015,2016,2017
X1,2,4,3
X2,2,2,3
X3,3,3,4
And then I try to combine them as well as transpose them with following functions. They are created by Ricardo Oliveros-Ramos at here and by Tony Cookson at here.
1. Firstly, I create function read.tcsv
to read and transpose data in CSV file
read.tcsv = function(file, header=TRUE, sep=",", ...) {
n = max(count.fields(file, sep=sep), na.rm=TRUE)
x = readLines(file)
.splitvar = function(x, sep, n) {
var = unlist(strsplit(x, split=sep))
length(var) = n
return(var)
}
x = do.call(cbind, lapply(x, .splitvar, sep=sep, n=n))
x = apply(x, 1, paste, collapse=sep)
out = read.csv(text=x, sep=sep, header=header, ...)
return(out)
}
2. Then I use multrbind.fill
to combine and fill missing value
multrbind.fill = function(mypath){
filenames=list.files(path=mypath, full.names=TRUE)
datalist = lapply(filenames, function(x){
read.tcsv(file=x,header=T)
}
)
Reduce(function(x,y) {plyr::rbind.fill(x,y)}, datalist)
}
- The result looks good:
ï..T X1 X2 X3
2015 1 1 1
2016 2 2 3
2017 3 2 4
2018 2 3 2
2015 2 2 3
2016 4 2 3
2017 3 3 4
- However, I want to add a column as an identifier for each file with their file name (or unique IDs) like that:
ï..T ID X1 X2 X3
2015 A 1 1 1
2016 A 2 2 3
2017 A 3 2 4
2018 A 2 3 2
2015 B 2 2 3
2016 B 4 2 3
2017 B 3 3 4
Someone help me!? Thanks in advance.