如何将函数应用于 R 中的多个变量?
How to apply a function to several variables in R?
我在 R 中有一个 simple/confusing 问题。
这是我的问题的一个例子。
我有一串数字或字符:
data <- c(1,2,3,4,5)
我有一个函数,我想将其应用于字符串中的多个变量。
dd <- function(d){if(d==data[1:3]) 'yes'
else 'no'}
但是当我将函数应用于字符串时出现此错误
unlist(lapply(data,dd))
警告信息:
1: In if (d == data[1:3]) "yes" :
the condition has length > 1 and only the first element will be used
2: In if (d == data[1:3]) "yes" :
the condition has length > 1 and only the first element will be used
3: In if (d == data[1:3]) "yes" :
the condition has length > 1 and only the first element will be used
4: In if (d == data[1:3]) "yes" :
the condition has length > 1 and only the first element will be used
5: In if (d == data[1:3]) "yes" :
the condition has length > 1 and only the first element will be used
所以,我的问题是如何将函数应用于字符串中的多个变量,而不仅仅是第一个元素?
获得类似
的输出
"yes" "yes" "yes" "no" "no"
提前致谢,
不需要 lapply
循环。可以使用向量化的ifelse
,需要使用%in%
:ifelse(d %in% data[1:3], "yes", "no")
回答您评论中的后续问题:
It works but how can I apply this to for example: if I want to have 'yes' for c(1,2) and 'no' for '3' and 'None' to the rest (4,5)?
有几种方法可以实现。您可以使用嵌套的 ifelse
。但是,在具体示例中,我将使用 cut
:
cut(data, breaks = c(-Inf, 2, 3, Inf), labels = c("yes", "no", "None"))
#[1] yes yes no None None
#Levels: yes no None
我在 R 中有一个 simple/confusing 问题。
这是我的问题的一个例子。
我有一串数字或字符:
data <- c(1,2,3,4,5)
我有一个函数,我想将其应用于字符串中的多个变量。
dd <- function(d){if(d==data[1:3]) 'yes'
else 'no'}
但是当我将函数应用于字符串时出现此错误
unlist(lapply(data,dd))
警告信息:
1: In if (d == data[1:3]) "yes" :
the condition has length > 1 and only the first element will be used
2: In if (d == data[1:3]) "yes" :
the condition has length > 1 and only the first element will be used
3: In if (d == data[1:3]) "yes" :
the condition has length > 1 and only the first element will be used
4: In if (d == data[1:3]) "yes" :
the condition has length > 1 and only the first element will be used
5: In if (d == data[1:3]) "yes" :
the condition has length > 1 and only the first element will be used
所以,我的问题是如何将函数应用于字符串中的多个变量,而不仅仅是第一个元素? 获得类似
的输出"yes" "yes" "yes" "no" "no"
提前致谢,
不需要 lapply
循环。可以使用向量化的ifelse
,需要使用%in%
:ifelse(d %in% data[1:3], "yes", "no")
回答您评论中的后续问题:
It works but how can I apply this to for example: if I want to have 'yes' for c(1,2) and 'no' for '3' and 'None' to the rest (4,5)?
有几种方法可以实现。您可以使用嵌套的 ifelse
。但是,在具体示例中,我将使用 cut
:
cut(data, breaks = c(-Inf, 2, 3, Inf), labels = c("yes", "no", "None"))
#[1] yes yes no None None
#Levels: yes no None