删除由rowname()作为id

时间:2018-09-03 14:34:01

标签: r

我知道有一些类似的问题。但是,对于他们来说,答案对我而言无济于事,或者我的理解是对的。

我的示例代码

set.seed(0)

df <- data.frame(A = seq(20),
                 B1 = sample(c(T, F), 20, replace=T),
                 B2 = sample(c(T, F), 20, replace=T))

rownames(df) <- df$A
df <- df[, c('B1', 'B2'), drop = FALSE]

result <- df[df$B1 == FALSE & df$B2 == FALSE, ]

print(result)

结果

> result
      B1    B2
1  FALSE FALSE
4  FALSE FALSE
10 FALSE FALSE
16 FALSE FALSE
18 FALSE FALSE

所以您最后看到5个案例。我希望从原始数据中删除这5种情况。框架df 不要松动rownames()或命名行。因此,应删除名称为1, 4, 10, 16, 18的行,而不会导致其他行的重命名。

我尝试过的方法(基于其他答案):

> library(dplyr)
> anti_join(df, result)
Joining, by = c("B1", "B2")
      B1    B2
1   TRUE FALSE
2   TRUE  TRUE
3  FALSE  TRUE
4   TRUE  TRUE
5  FALSE  TRUE
6  FALSE  TRUE
7  FALSE  TRUE
8   TRUE  TRUE
9   TRUE  TRUE
10  TRUE FALSE
11 FALSE  TRUE
12  TRUE  TRUE
13  TRUE FALSE
14 FALSE  TRUE
15  TRUE FALSE

此处的行名不正确。它们只是从1到15。

另一种尝试对我毫无意义

> setdiff(df, result)
     B1    B2
1  TRUE FALSE
2  TRUE  TRUE
3 FALSE  TRUE

2 个答案:

答案 0 :(得分:3)

带有setdiff的选项为:

df[setdiff(rownames(df), rownames(result)), ]

#      B1    B2
#2   TRUE FALSE
#3   TRUE  TRUE
#5  FALSE  TRUE
#6   TRUE  TRUE
#7  FALSE  TRUE
#8  FALSE  TRUE
#9  FALSE  TRUE
#11  TRUE  TRUE
#12  TRUE  TRUE
#13  TRUE FALSE
#14 FALSE  TRUE
#15  TRUE  TRUE
#17  TRUE FALSE
#19 FALSE  TRUE
#20  TRUE FALSE

但是,我建议的更通用的方法是只计算一次索引并使用它们。

inds <- df$B1 == FALSE & df$B2 == FALSE
result <- df[inds, ]
output <- df[!inds, ]

答案 1 :(得分:2)

我们可以将class NameForm extends React.Component { constructor(props) { super(props); this.state = {value: ''}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({value: event.target.value}); } handleSubmit(event) { alert('A name was submitted: ' + this.state.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" value={this.state.value} onChange={this.handleChange} /> </label> <input type="submit" value="Submit" /> </form> ); } } ReactDOM.render( <NameForm />, document.getElementById('root') ); %in%一起使用

!
相关问题