你能帮我解决以下问题吗?
这是我在R中的一个可复制的df例子:
name <- c("cat", "dog", "fish", "chicken", "dino")
age <- c(29, 30, 100, 12, 1000)
start_pos <- c(1, 2, 3, 4, 5)
end_pos <- c(1, 2, 5, 7, 5)
df <- data.frame(name, age, start_pos, end_pos,
stringsAsFactors = F)
df
我正在尝试对这些数据进行排序,以便只有当列的end_pos-start_pos等于0时,我才能在df中包含这些列。所以,只有猫、狗和恐龙应该呆在df里。
我想用if-else语句,比如
if(end_pos-start_pos=0){
print("yes")
}
然而,错误开始出现。使用if-else语句来解决此任务是一种好方法吗?你能给我推荐另一种思考这项任务的方式吗?
提前感谢!
最简单的事情可能是通过逻辑条件来subset
。
subset(df, start_pos - end_pos == 0)
# name age start_pos end_pos
# 1 cat 29 1 1
# 2 dog 30 2 2
# 5 dino 1000 5 5
library(data.table)
setDT(df)[start_pos == end_pos]
name age start_pos end_pos
1: cat 29 1 1
2: dog 30 2 2
3: dino 1000 5 5
作为ifelse()
的替代方案,您可以使用dplyr
包的filter()
函数,如以下
library(dplyr)
df %>% filter(start_pos == end_pos)
如果要使用基数R,则可以使用df[df$start_pos == df$end_pos, ]
。