通过删除一些NA单元来压缩数据帧?

时间:2018-08-05 19:54:18

标签: r loops dataframe lapply na

如果我有如下数据框:

data.frame(
  cola = c(3,NA,NA),
  colb = c(1,NA,NA),
  colc = c(NA,6,NA),
  cold = c(NA,7,NA),
  cole = c(NA,3,NA),
  colf = c(NA,NA,9), 
  colg = c(NA,NA,8)
)

如何将所有字段向左移动,按需消除NA值,如下所示:

data.frame(
  cola = c(3,6,9),
  colb = c(1,7,8),
  colc = c(NA,3,NA)
)

感谢您的帮助。

3 个答案:

答案 0 :(得分:5)

我们遍历行,使用NA删除na.omit元素,然后根据NA的最大长度在末尾附加list

lst <- apply(df1, 1, na.omit)
out <- as.data.frame(do.call(rbind, lapply(lst, `length<-`, max(lengths(lst)))))

答案 1 :(得分:3)

另一个选择可能是:

  public void initCountdown(_Release release) {
    /*
    DateTime releaseDate = new DateTime(release.getDate()).withZone(DateTimeZone.UTC);
    DateTime currentDate = DateTime.now().withZone(DateTimeZone.UTC);
    long timeTillRelease = Seconds.secondsBetween(currentDate, releaseDate).getSeconds();
    long days = TimeUnit.MILLISECONDS.toDays(timeTillRelease);
    */
    Calendar calReleaseDate = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    calReleaseDate.setTimeInMillis(release.getDate());
    calReleaseDate.set(Calendar.HOUR_OF_DAY, 0);
    calReleaseDate.set(Calendar.MINUTE, 0);
    calReleaseDate.set(Calendar.SECOND, 0);
    calReleaseDate.set(Calendar.MILLISECOND, 0);
    long timeTillRelease =  calReleaseDate.getTimeInMillis() - Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis();
    long seconds = TimeUnit.MILLISECONDS.toSeconds(timeTillRelease);
    // Period period = new Period(currentDate, releaseDate, PeriodType.millis());
    mCountdownTimer = new CountDownTimer(seconds * 1000 , 1000) { // adjust the milli seconds here
        public void onTick(long millisUntilFinished) {
            // 1 sec = 1000 millis
            long seconds = millisUntilFinished / 1000;
            long minutes = seconds / 60;
            long hours = minutes / 60;
            long days = hours / 24;
            mDaysTxt.setText(String.valueOf(days));
            mHoursText.setText(String.valueOf(hours % 24));
            mMinutesText.setText(String.valueOf(minutes % 60));
            mSecondsText.setText(String.valueOf(seconds % 60));
        }

        public void onFinish() {
            mHeaderReleasesTitle.setText("Released on");
            mOutNowTxt.setVisibility(View.VISIBLE);
            mCountdownLayout.setVisibility(View.GONE);
        }
    };
    mCountdownTimer.start();

    long updatedAt = release.getUpdated_at();
    if (updatedAt != 0) {
        mTxtLastUpdatedOnRelease.setText("Release date last updated on " + mDateFormatter.format(updatedAt));
    }
}

答案 2 :(得分:1)

您可以转置,放下NA,然后转回:

library(magrittr)
library(data.table)

DF %>% transpose %>% lapply(na.omit) %>% transpose %>% 
  data.frame %>% setNames(names(DF)[seq_along(.)])

  cola colb colc
1    3    1   NA
2    6    7    3
3    9    8   NA