简体   繁体   English

重新排列R中的数据框

[英]Rearranging a data frame in R

The following R code generates a snippet from data frame I am working with at the moment: 以下R代码生成我正在处理的数据框的片段:

rep1 <- c("20/02/01","23/03/02")
rep2 <- c(NA, "03/05/02")
rep3 <- c("16/04/01",NA)
rep4 <- c(NA,"12/02/03")
data <- data.frame(rep1 = rep1, rep2 = rep2, rep3 = rep3, rep4 = rep4)

The data frame generated by the code looks like this: 代码生成的数据框如下所示:

      rep1     rep2     rep3     rep4
1 20/02/01     <NA> 16/04/01     <NA>
2 23/03/02 03/05/02     <NA> 12/02/03

I would like to rearrange this data frame so it looks like this: 我想重新排列这个数据框,所以它看起来像这样:

      rep1     rep2   rep3     rep4
1 20/02/01 16/04/01    <NA>     <NA>
2 23/03/02 03/05/02   12/02/03   <NA> 

That is, for every row I would like to replace every NA with the next entry in the row, untill there are only NAs left in the row. 也就是说,对于每一行,我想用行中的下一个条目替换每个NA,直到该行中只剩下NAs。

The true data frame consists of many thousand rows, so doing this by hand would mean many late hours in the office. 真正的数据框由数千行组成,因此手动执行此操作意味着办公室的许多工作时间。

If anyone could tell me how to do this in R, I would be most grateful! 如果有人能告诉我如何在R中这样做,我将非常感激!

I'm not sure I understand, but it seems you want to move the NA's to the end columns? 我不确定我理解,但似乎你想把NA移到最后一列? Here is one way (done quickly; there may be a cleaner way): 这是一种方式(快速完成;可能有更简洁的方式):

> d <- data.frame(rbind(c(1, 2, NA, 4, NA, 6), c(NA, 2, 3, 4, 5, 6)))
> d
  X1 X2 X3 X4 X5 X6
1  1  2 NA  4 NA  6
2 NA  2  3  4  5  6
> t(apply(d, 1, function(x) c(x[!is.na(x)], rep(NA, sum(is.na(x))))))
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    2    4    6   NA   NA
[2,]    2    3    4    5    6   NA

On your data: 关于你的数据:

> t(apply(data, 1, function(x) c(x[!is.na(x)], rep(NA, sum(is.na(x))))))
     [,1]       [,2]       [,3]       [,4]
[1,] "20/02/01" "16/04/01" NA         NA  
[2,] "23/03/02" "03/05/02" "12/02/03" NA  

按照文斯的建议,但也许有点清洁:

t(apply(d, 1, function(x) x[order(x)]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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