R 如何基于行值选择列
有没有办法过滤像这样的data.frame?我希望保留出现某个子字符串的所有行和列,以及下一列R 如何基于行值选择列,r,dataframe,R,Dataframe,有没有办法过滤像这样的data.frame?我希望保留出现某个子字符串的所有行和列,以及下一列 df <- read.table(header=TRUE, stringsAsFactors = FALSE, text = "date col2 col3 col4 col5 col6 1 boston 22 new_york 15 atlanta 5
df <- read.table(header=TRUE, stringsAsFactors = FALSE, text =
"date col2 col3 col4 col5 col6
1 boston 22 new_york 15 atlanta 5
2 boston 21 new_york 15 atlanta 0
")
cities <- c('boston', 'atlanta')
#filter by cities
#output
#col2 col3 col5 col6
#boston 22 atlanta 5
#boston 21 atlanta 0
df我们循环遍历数据集的备用列,检查%
cities中的所有元素是否都是%,以创建一个逻辑向量('i1'),然后根据索引,获得真实列和下一列的列索引
i1 <- sapply(df[c(TRUE, FALSE)], function(x) all(x %in% cities))
df[sort(which(names(df) %in% names(i1)[i1]) + rep(0:1, each = 2))]
我们循环遍历数据集的备用列,检查%
城市中的所有元素是否都是%,以创建一个逻辑向量('i1'),然后根据索引,获得真实列和下一列的列索引
i1 <- sapply(df[c(TRUE, FALSE)], function(x) all(x %in% cities))
df[sort(which(names(df) %in% names(i1)[i1]) + rep(0:1, each = 2))]