我有一个数据帧:
| x | y |
|---|---|
| a | e |
| b | f |
| c | g |
| d | h |
Run Code Online (Sandbox Code Playgroud)
我有一个bool值的数据框如下:
| x | y |
|-------|-------|
| FALSE | TRUE |
| FALSE | TRUE |
| TRUE | FALSE |
| TRUE | FALSE |
Run Code Online (Sandbox Code Playgroud)
(实际上这个东西来自不同的帖子,但这不是真正的相关因为这是一个独立的问题)
我只是在寻找一种方法来将带有bool值的df应用到'常规'df,并获得:
| x | y |
|---|---|
| | e |
| | f |
| c | |
| d | |
Run Code Online (Sandbox Code Playgroud)
这个问题提出了一个非常相似的问题,但解决方案分道扬..
我尝试了各种不同的索引方案,但它们都无法保留我想要的输出的矩形结构.
df[mask] 太好了,也不是真的.
任何建议都非常感谢.
我的数据:
df <- data.frame(
x = c('a', 'b', 'c', 'd'),
y = c('e', 'f', 'g', 'h'), stringsAsFactors = F
)
mask <- structure(list(x = c(FALSE, FALSE, TRUE, TRUE), y = c(TRUE, TRUE,
FALSE, FALSE)), .Names = c("x", "y"), row.names = c(NA, -4L), class = "data.frame")
Run Code Online (Sandbox Code Playgroud)
最简单的方法是(感谢@thelatemail的灵感)
df[!mask] <- ""
# x y
# 1 e
# 2 f
# 3 c
# 4 d
Run Code Online (Sandbox Code Playgroud)
这是因为!强制mask逻辑矩阵(因此不需要as.matrix()呼叫)
str(mask)
# 'data.frame': 4 obs. of 2 variables:
# $ x: logi FALSE FALSE TRUE TRUE
# $ y: logi TRUE TRUE FALSE FALSE
str(!mask)
# logi [1:4, 1:2] TRUE TRUE FALSE FALSE FALSE FALSE ...
# - attr(*, "dimnames")=List of 2
# ..$ : NULL
# ..$ : chr [1:2] "x" "y"
## and
class(!mask)
# "matrix"
Run Code Online (Sandbox Code Playgroud)
一些ifelses也会起作用
df$x <- ifelse(mask$x, df$x, "")
df$y <- ifelse(mask$y, df$y, "")
Run Code Online (Sandbox Code Playgroud)
您可以循环遍历列mapply,检查以下值mask:
as.data.frame( mapply(function(x,y) ifelse(y, x, ''), df, mask))
## x y
## 1 e
## 2 f
## 3 c
## 4 d
Run Code Online (Sandbox Code Playgroud)
我们可以用 replace
replace(df, !mask, "")
# x y
#1 e
#2 f
#3 c
#4 d
Run Code Online (Sandbox Code Playgroud)