사용자 정의 기능은 replace_matching()
입니다. ...
d <- data.frame(a = 1:10)
for (i in 2:10) {
d[[letters[i]]] <- 1:10
}
rownames(d) <- letters[10:1]
d
#> a b c d e f g h i j
#> j 1 1 1 1 1 1 1 1 1 1
#> i 2 2 2 2 2 2 2 2 2 2
#> h 3 3 3 3 3 3 3 3 3 3
#> g 4 4 4 4 4 4 4 4 4 4
#> f 5 5 5 5 5 5 5 5 5 5
#> e 6 6 6 6 6 6 6 6 6 6
#> d 7 7 7 7 7 7 7 7 7 7
#> c 8 8 8 8 8 8 8 8 8 8
#> b 9 9 9 9 9 9 9 9 9 9
#> a 10 10 10 10 10 10 10 10 10 10
기능 ...
replace_matching <- function(df, replace_with = NA) {
# Find all combinations of row and column names
name_grid <- expand.grid(rownames(df), colnames(df), stringsAsFactors = FALSE)
# Find any names with matches
matched_names <- name_grid$Var1[name_grid$Var1 == name_grid$Var2]
# Wherever there are matches, set cell to NA
for (mn in matched_names) {
df[mn, mn] <- replace_with
}
return(df)
}
기본 유스 케이스 ... 여기
일부 장난감 데이터를 : 그것은 심지어는 세포에 삽입 할 것을 조정하게됩니다 -99 기본적 교체 값을 변경
replace_matching(d)
#> a b c d e f g h i j
#> j 1 1 1 1 1 1 1 1 1 NA
#> i 2 2 2 2 2 2 2 2 NA 2
#> h 3 3 3 3 3 3 3 NA 3 3
#> g 4 4 4 4 4 4 NA 4 4 4
#> f 5 5 5 5 5 NA 5 5 5 5
#> e 6 6 6 6 NA 6 6 6 6 6
#> d 7 7 7 NA 7 7 7 7 7 7
#> c 8 8 NA 8 8 8 8 8 8 8
#> b 9 NA 9 9 9 9 9 9 9 9
#> a NA 10 10 10 10 10 10 10 10 10
...
SimonJackson의 데이터 @ 사용
replace_matching(d, -99)
#> a b c d e f g h i j
#> j 1 1 1 1 1 1 1 1 1 -99
#> i 2 2 2 2 2 2 2 2 -99 2
#> h 3 3 3 3 3 3 3 -99 3 3
#> g 4 4 4 4 4 4 -99 4 4 4
#> f 5 5 5 5 5 -99 5 5 5 5
#> e 6 6 6 6 -99 6 6 6 6 6
#> d 7 7 7 -99 7 7 7 7 7 7
#> c 8 8 -99 8 8 8 8 8 8 8
#> b 9 -99 9 9 9 9 9 9 9 9
#> a -99 10 10 10 10 10 10 10 10 10
아마도 거리가 0 인 인스턴스는 행 이름이 열 이름과 동일한 경우 일 수 있습니다. min() 함수에 포함되지 않도록 NA를 0으로 대체 할 수 있습니까? –
그냥 대각선입니까? 'diag (df) <- NA'? – thelatemail
'df
thelatemail