-3

I am new with r. I need help.

I have loaded into r-studio a list with 89 elements and each element has 13149 rows with years. I have to eliminate the following years 1982, 1983, 1997, 1998 from the 89 elements. After that, I have to export each element as text file.

I have upload a link to see a picture of what I am talking about.

enter image description here

What I did was

# LOAD THE DATA
files <- list.files(pattern = '*.txt', full.names = TRUE)
data <- lapply(files, read.table)
df <- do.call(rbind, data)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Pleas read [this post](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on how to ask a good question in R and edit your post. Particularly, please use ``dput()`` to share your data rather than posting images. – user438383 Jan 10 '21 at 10:39

1 Answers1

0

Assuming there is a column called year in each of the file you can try :

files <- list.files(pattern = '*.txt', full.names = TRUE)

lapply(files, function(x) {
  tmp <- subset(read.table(x), !year %in% c(1982, 1983, 1997, 1998))
  write.table(tmp, paste0(tools::file_path_sans_ext(basename(x)), '_new.txt'))
})
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • I tried your code and it says " Error in Year %in% c(1982, 1983, 1997, 1998) : object 'Year' not found " But the column year is there because I tried in different way like having one data frame with all the columns and rows and I applied this code df <- subset(df,!Year %in% c(1982, 1983, 1997, 1998),) write.table(df, file = "new.txt") But the problem is that I have saved it in one file instead of the independent ones. – Daniel Tobalina Jan 10 '21 at 14:47
  • @DanielTobalina What does `names(data[[1]])` return? Note that I have used `year` (lower case) in my answer and you might have `Year` (Y upper case) as column name. R is case-sensitive. – Ronak Shah Jan 10 '21 at 23:15