[英]How to apply a function to several variables in R?
我在R中有一個簡單/令人困惑的問題。
這是我的問題的一個例子。
我有一串數字或字符:
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")
在您的評論中回答后續問題:
它可以工作,但是我如何將其應用於例如:如果我想對c(1,2)使用'yes',對其余部分(4,5)使用'no'表示'3'和'None'?
有幾種方法可以實現這一目標。 您可以使用嵌套的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.