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

Move data from specific row from one column to the adjacent row to the next column in R

I have a data frame with three columns:


df <- data.frame(col1=c('71711', '71711',  '71711', 'Comment 4', '71711', 'Comment 6'),
                  col2=c('Comment 1','Comment 2','Comment 3', '24','Comment 5','26'),
                  col3 = c('21','22','23',NA,'25',NA))

Desired output:

Col1    Col2   Col3
71711   Comment 1   21
71711   Comment 2   22
71711   Comment 3   23
71711   Comment 4   24
71711   Comment 5   25
71711   Comment 6   26


I tried the following but it replaces desired values with numeric one:

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

for (i in 1:nrow(df))
  {
  
  if  (any(sapply(df$col2, is.numeric)) == "True" )
       df$col3[i] <- df$col2[i]
       df$col1[i] <- df$col2[i]

}

Thanks

>Solution :

You can find rows which have NA in col3 and just ‘shift’ values:

indices <- which(is.na(df$col3))
df[indices,] <- append(list(paste0("ID", indices)), df[indices,-3])
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