미확인 열을 무시하면서 데이터 프레임 열을 재정렬합니다

StackOverflow https://stackoverflow.com/questions/1538798

  •  20-09-2019
  •  | 
  •  

문제

나는 이것을하는 더 좋은 방법이 있다고 생각합니다.

데이터 프레임에서 열을 재정렬하려고합니다. 목록이 있습니다. ordered.colnames, 새로운 질서를 대표하지만 - 그러나 일부 열은 존재하지 않습니다 안에 dataset. 오류를 피하려면 "undefined columns selected", 나는 관련 슬라이싱을 a try() 기능.

다음 방법이 작동하지만 더 좋은 방법이 있습니까?

> ordered.colnames[1:5]
[1] "lady_22102"         "attentions_83249"   "perseverance_17864"
[4] "cecil_84477"        "cecilia_133476"

dataset.reordered = c() 
for (i in 1:length(ordered.colnames)) {
    col = NA
    col = try(cbind(dataset[,ordered.colnames[i]]),silent=TRUE)
    if (!inherits(col,"try-error")) {
        colnames(col) = ordered.colnames[i]
        dataset.reordered = cbind(dataset.reordered, col) 
    }
}
도움이 되었습니까?

해결책

그냥 할 수 없습니까?

ordered.colnames <- ordered.colnames[ordered.colnames %in% colnames(dataset)]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top