Reputation: 9986
I have two files. One file (csv
) contains data, and second contains header for data (in one column). I need to unite both files and get data.frame
with data from first file and header from second file. How it can be done?
Reduced sample. Data file:
10;21;36
7;56;543
7;7;7
7890;1;1
Header file:
height
weight
light
I need data.frame
as from csv
file:
height;weight;light
10;21;36
7;56;543
7;7;7
7890;1;1
Upvotes: 0
Views: 598
Reputation: 99331
You could use the col.names
argument in read.table()
to read the header file as the column names in the same call used to read the data file.
read.table(datafile, sep = ";", col.names = scan(headerfile, what = ""))
As @chinsoon12 shows in the comments, readLines()
could also be used in place of scan()
.
Upvotes: 2
Reputation: 887153
We can read both the datasets with header=FALSE
and change the column names with the first column of second dataset.
df1 <- read.csv("firstfile.csv", sep=";", header=FALSE)
df2 <- read.csv("secondfile.csv", header=FALSE)
colnames(df1) <- as.character(df2[,1])
Upvotes: 1