Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

How can I eliminate rows from lists in r

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)
question from:https://stackoverflow.com/questions/65652125/how-can-i-eliminate-rows-from-lists-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'))
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...