R 在数据帧的多个列中搜索
我对R不熟悉,它在快速处理数据和返回可读信息方面的能力让我大吃一惊。但现在,我被困住了 我有一个作为数据帧导入的大型数据集。我想使用regex(R 在数据帧的多个列中搜索,r,plyr,dplyr,R,Plyr,Dplyr,我对R不熟悉,它在快速处理数据和返回可读信息方面的能力让我大吃一惊。但现在,我被困住了 我有一个作为数据帧导入的大型数据集。我想使用regex(grepl?)在数据框的特定列中搜索,并将搜索结果放入新列中。我以为我可以用apply或ddply来实现这一点,但我似乎不能很好地围绕函数来完成这一点 这是一个示例数据帧 df <- structure(list(w = structure(c(3L, 2L, 1L, 3L, 3L), .Label = c("b", "c", "d"), cla
grepl
?)在数据框的特定列中搜索,并将搜索结果放入新列中。我以为我可以用apply
或ddply
来实现这一点,但我似乎不能很好地围绕函数来完成这一点
这是一个示例数据帧
df <- structure(list(w = structure(c(3L, 2L, 1L, 3L, 3L), .Label = c("b",
"c", "d"), class = "factor"), x = structure(c(1L, 2L, 1L, 2L,
3L), .Label = c("a", "b", "d"), class = "factor"), y = structure(c(2L,
1L, 1L, 1L, 1L), .Label = c("a", "d"), class = "factor")), .Names = c("w",
"x", "y"), row.names = c(NA, -5L), class = "data.frame")
我试过:
search这不需要正则表达式。您可以使用行和
当我们使用df==“d”
时,整个数据帧将转换为逻辑值。由于FALSE
在数字上等于零,因此任何大于零的行和都意味着该行至少包含一个“d”
关于参考资料,我认为学习R最好的地方是从编写R的人那里。请查看手册,也可以使用以下网址:
df$result = apply(df, 1, function(x) any(grepl("d",x)))
df
w x y result
1 d a d TRUE
2 c b a FALSE
3 b a a FALSE
4 d b a TRUE
5 d d a TRUE
w x y
[1,] TRUE FALSE TRUE
[2,] FALSE FALSE FALSE
[3,] FALSE FALSE FALSE
[4,] TRUE FALSE FALSE
[5,] TRUE TRUE FALSE
w x y z
1 d a d TRUE
2 c b a FALSE
3 b a a FALSE
4 d b a TRUE
5 d d a TRUE
> df$z <- rowSums(df == "d") > 0
> df
# w x y z
# 1 d a d TRUE
# 2 c b a FALSE
# 3 b a a FALSE
# 4 d b a TRUE
# 5 d d a TRUE
fun <- function(data, what) {
data$z <- rowSums(data == what) > 0
data
}
fun(df, "b")
fun(df, "d")
lapply(c("a", "b"), fun, data = df)
df$z <- apply(df == "d", 1, any)
df$result = apply(df, 1, function(x) any(grepl("d",x)))
df
w x y result
1 d a d TRUE
2 c b a FALSE
3 b a a FALSE
4 d b a TRUE
5 d d a TRUE