모든 0 값을 NA로 교체
숫자 열이있는 데이터 프레임이 있습니다. 일부 행에는 통계 분석에서 null로 간주되어야하는 0 값이 있습니다. R에서 0 값을 모두 NULL로 바꾸는 가장 빠른 방법은 무엇입니까?
모든 0을 NA로 바꾸기 :
df[df == 0] <- NA
설명
1.NULL
0을 바꾸려 는 것이 아닙니다 . 이 글은 말하기를 ?'NULL'
,
NULL은 R의 null 객체를 나타냅니다.
독특하고 가장 유익하지 않은 빈 개체로 볼 수 있습니다. 1 그렇게 놀라운 것은 아닙니다.
data.frame(x = c(1, NULL, 2))
# x
# 1 1
# 2 2
즉, R은이 널 오브젝트를위한 공간을 예약하지 않습니다. 2 한편, ?'NA'
우리는
NA는 결 측값 표시기를 포함하는 길이 1의 논리 상수입니다. NA는 raw를 제외한 다른 벡터 유형으로 강제 변환 할 수 있습니다.
중요한 NA
것은 R의 공간을 확보 할 수 있도록 길이가 1입니다. 예 :
data.frame(x = c(1, NA, 2))
# x
# 1 1
# 2 NA
# 3 2
또한 데이터 프레임 구조에서는 "구멍"(즉, NULL
값) 이 없도록 모든 열에 동일한 수의 요소가 있어야합니다 .
이제 NULL
적어도 하나의 0을 포함하는 모든 행을 완전히 제거한다는 의미에서 데이터 프레임에서 0을 대체 할 수 있습니다. 사용하는 경우, 예를 들면, var
, cov
, 또는 cor
, 그 제 제로로 대체 실제로 동등한 NA
및의 값의 설정 use
등을 "complete.obs"
. 그러나 일반적으로 추가 정보가 손실되므로 만족스럽지 않습니다.
2. 솔루션에서 df == 0
벡터화를 사용하여 일종의 루프를 실행하는 대신 . df == 0
반환 (그것을 시도)와 동일한 크기의 행렬 df
항목과, TRUE
그리고 FALSE
. 또한이 행렬을 서브셋으로 전달할 수도 있습니다 [...]
(참조 ?'['
). 마지막으로 결과 df[df == 0]
가 완벽하게 직관적이지만 df[df == 0] <- NA
원하는 효과 를 주는 것은 이상하게 보일 수 있습니다 . 할당 연산자 <-
는 실제로 항상 똑똑하지는 않지만 다른 객체에서는 이런 방식으로 작동하지 않지만 데이터 프레임에서는 작동합니다. 참조하십시오 ?'<-'
.
1 세트 이론의 빈 세트는 어떻게 든 관련이 있습니다.
2 집합 이론과의 또 다른 유사점 : 빈 집합은 모든 집합의 부분 집합이지만 공간을 예약하지는 않습니다.
Let me assume that your data.frame is a mix of different datatypes and not all columns need to be modified.
to modify only columns 12 to 18 (of the total 21), just do this
df[, 12:18][df[, 12:18] == 0] <- NA
An alternative way without the [<-
function:
A sample data frame dat
(shamelessly copied from @Chase's answer):
dat
x y
1 0 2
2 1 2
3 1 1
4 2 1
5 0 0
Zeroes can be replaced with NA
by the is.na<-
function:
is.na(dat) <- !dat
dat
x y
1 NA 2
2 1 2
3 1 1
4 2 1
5 NA NA
dplyr::na_if()
is an option:
library(dplyr)
df <- data_frame(col1 = c(1, 2, 3, 0),
col2 = c(0, 2, 3, 4),
col3 = c(1, 0, 3, 0),
col4 = c('a', 'b', 'c', 'd'))
na_if(df, 0)
# A tibble: 4 x 4
col1 col2 col3 col4
<dbl> <dbl> <dbl> <chr>
1 1 NA 1 a
2 2 2 NA b
3 3 3 3 c
4 NA 4 NA d
#Sample data
set.seed(1)
dat <- data.frame(x = sample(0:2, 5, TRUE), y = sample(0:2, 5, TRUE))
#-----
x y
1 0 2
2 1 2
3 1 1
4 2 1
5 0 0
#replace zeros with NA
dat[dat==0] <- NA
#-----
x y
1 NA 2
2 1 2
3 1 1
4 2 1
5 NA NA
Because someone asked for the Data.Table version of this, and because the given data.frame solution does not work with data.table, I am providing the solution below.
Basically, use the :=
operator --> DT[x == 0, x := NA]
library("data.table")
status = as.data.table(occupationalStatus)
head(status, 10)
origin destination N
1: 1 1 50
2: 2 1 16
3: 3 1 12
4: 4 1 11
5: 5 1 2
6: 6 1 12
7: 7 1 0
8: 8 1 0
9: 1 2 19
10: 2 2 40
status[N == 0, N := NA]
head(status, 10)
origin destination N
1: 1 1 50
2: 2 1 16
3: 3 1 12
4: 4 1 11
5: 5 1 2
6: 6 1 12
7: 7 1 NA
8: 8 1 NA
9: 1 2 19
10: 2 2 40
You can replace 0
with NA
only in numeric fields (i.e. excluding things like factors), but it works on a column-by-column basis:
col[col == 0 & is.numeric(col)] <- NA
With a function, you can apply this to your whole data frame:
changetoNA <- function(colnum,df) {
col <- df[,colnum]
if (is.numeric(col)) { #edit: verifying column is numeric
col[col == -1 & is.numeric(col)] <- NA
}
return(col)
}
df <- data.frame(sapply(1:5, changetoNA, df))
Although you could replace the 1:5
with the number of columns in your data frame, or with 1:ncol(df)
.
참고URL : https://stackoverflow.com/questions/11036989/replace-all-0-values-to-na
'development' 카테고리의 다른 글
Bash에서 두 개의 부동 소수점 숫자를 비교하는 방법은 무엇입니까? (0) | 2020.07.14 |
---|---|
Oracle PL / SQL-간단한 배열 변수를 만드는 방법은 무엇입니까? (0) | 2020.07.14 |
목록에서 면도기 드롭 다운 목록 채우기 (0) | 2020.07.14 |
Github 푸시 오류 : RPC 실패; (0) | 2020.07.14 |
속성 파일에서 값을 읽는 방법은 무엇입니까? (0) | 2020.07.14 |