简体   繁体   中英

merge every other row in R

I have this dataframe where the id and values are on two alternating rows.

278             
8134134 87903   98732   1248    
9907        
3134 1450893    1345807 1234    555    
23              
23487   12347   3407        

I am trying to append the values to the ids so they are on the same row.

278 8134134 87903   98732   1248    
9907    3134    1450893 1345807 1234    555    
23  23487   12347   3407    

(Also wondering how to format tables in these questions!)

It's unclear what your data structure really looks like. I've taken my best guess. In principle, you can get alternate rows using a c(TRUE, FALSE) index and relying on recycling.

df <- 
  data.frame(x = c("278",
                   "8134134 87903 98732 1248",
                   "9907",
                   "3134 1450893 1345807 1234 555",
                   "23",
                   "23487 12347 3407"),
             stringsAsFactors = FALSE)

cbind(df[c(TRUE, FALSE), ],
      df[c(FALSE, TRUE), ])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM