问题描述
id first middle last Age
1 Carol Jenny Smith 15
2 Sarah Carol Roberts 20
3 Josh David Richardson 22
我正在尝试在任何名称列(第一,中间,最后)中找到一个特定名称.例如,如果我找到了一个名字叫Carol的人(无论名字/中间名/姓氏都没关系),我想对"Carol"列进行突变并给出1.所以我想要的是以下
I am trying find a specific name in ANY of the name columns (first, middle, last). For example, if I found anyone with a name Carol (doesn't matter if it's the first/middle/last name), I want to mutate a column 'Carol' and give 1. So what I want is the following
id first middle last Age Carol
1 Carol Jenny Smith 15 1
2 Sarah Carol Roberts 20 1
3 Josh David Richardson 22 0
我一直在尝试ifelse(c(first,middle,last)=="Carol",1,0)或"Carol"%in%首先...等但是由于某种原因,我只能处理一个专栏,而不是多个专栏.有人可以帮助我吗?预先谢谢你!
I have been trying ifelse(c(first, middle,last) == "Carol" , 1, 0 )or "Carol" %in% first...etcbut for some reason I can only work on one column instead of multiple columns.. Could anyone help me please? Thank you in advance!
推荐答案
我们可以使用rowSums
df$Carol <- as.integer(rowSums(df[2:4] == "Carol") > 0)
df
# id first middle last Age Carol
#1 1 Carol Jenny Smith 15 1
#2 2 Sarah Carol Roberts 20 1
#3 3 Josh David Richardson 22 0
如果我们需要它作为功能
If we need it as a function
fun <- function(df, value) {
as.integer(rowSums(df[2:4] == value) > 0)
}
fun(df, "Carol")
#[1] 1 1 0
fun(df, "Sarah")
#[1] 0 1 0
,但这假设您要搜索的列位于位置2:4
.
but this assumes the columns you want to search are at position 2:4
.
为列位置提供更大的灵活性
To give more flexibility with column position
fun <- function(df, cols, value) {
as.integer(rowSums(df[cols] == value) > 0)
}
fun(df, c("first", "last","middle"), "Carol")
#[1] 1 1 0
fun(df, c("first", "last","middle"), "Sarah")
#[1] 0 1 0
这篇关于如何查找ANY列是否具有我要查找的特定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!