I am new to R. I have multiple files in a directory on my local pc. I have imported them to R and added column names as below. Now I need to add the year to each data frame which corresponds to the file name. For example the first file is called 1950 the 2nd 1951 and so on. How do I add the year as a column name with these values in R?
The output is below
Name Sex Number
1 Linda F 10
2 Mary F 100
3 Patrick M 200
4 Barbara F 300
5 Susan F 500
6 Richard M 900
7 Deborah F 500
8 Sandra F 23
9 Conor M 15
10 Conor F 120
I need another column at the start that is the year for this file?
This is my code to generate the above.
ldf <- list() # creates a list
listtxt <- dir(pattern = "*.txt") # creates the list of all the txt files in the directory
#Year = 1950
for (k in 1:length(listtxt)) #1:4 4 is the length of the list
{
ldf[[k]] <- read.table(listtxt[k],header=F,sep=",")
colnames(ldf[[k]]) = c('Name', 'Sex', 'Number')
#test = cbind(ldf[[k]], Year )
}
I need the year to increase by 1 for each file and to add it as a column with the value? Any help would be greatly appreciated.