Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For loop skipping columns in R

I want to concatenate text across 20 columns of my dataset (dat), skipping all NA values.

For example, if the first row had "cat" in column 1, "dog" in column 2, and NA in column 3, I want to compile that as "cat dog" in a new column (dat$results). Here’s what I have:

m <- ""

for(i in 1:20){
  if(!is.na(dat[,i])){
    m <- paste(m, dat[,i], sep = " ") 
  }
  else {
  next 
  }
}

dat$results <- m 

The loop only runs up to column 3 (which is NA for my first row). Not a problem for that first row, BUT other rows that do have text in column 3 don’t get that column compiled. What can I do here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Maybe just concatenate all the columns in one go and remove na‘s and double spaces afterward

dat$result <- gsub('\\s\\s', ' ', gsub('NA', '', do.call(paste, d[,1:20])))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading