简体   繁体   English

R-应用基于逻辑向量的函数

[英]R - Apply a function based on logical vector

I have the following code, but it throws the following error: 我有以下代码,但是会引发以下错误:

the condition has length > 1 and only the first element will be used

Obviously this means that I am misusing the if (condition) {action} construction, so I'm looking for a more elegant way to do this: 显然,这意味着我在滥用if (condition) {action}构造,因此我正在寻找一种更优雅的方法:

if (grepl("Spring", data$Survey)) {data["Season"] <- "Spring"}
if (grepl("Summer", data$Survey)) {data["Season"] <- "Summer"}
if (grepl("Fall", data$Survey)) {data["Season"] <- "Fall"}

Basically, I would like to input a logical vector, and for every TRUE , apply a function to a data set of the same length (in this case, assigning a string value to that row of a dataframe). 基本上,我想输入一个逻辑向量,并且对于每个TRUE ,将一个函数应用于相同长度的数据集(在这种情况下,将字符串值分配给数据帧的该行)。

You could do this in one step using eg stringr::str_extract . 您可以使用例如 stringr::str_extract一步完成此stringr::str_extract It will return <NA> if there is no match. 如果没有匹配项,它将返回<NA>

library(dplyr)
library(stringr)

data <- data.frame(Survey = sample(c("it's Spring yay",
                                     "it's Summer yay",
                                     "it's Fall yay"),
                            20, replace = TRUE))

data <- data %>% 
  mutate(Season = str_extract(Survey, "(Spring|Summer|Fall)"))

You can use ifelse which is vectorial instead of if : 您可以使用矢量的ifelse代替if

data$Season <- ifelse(grepl("Spring", data$Survey), 
                         "Spring", 
                         ifelse(grepl("Summer", data$Survey), 
                                "Summer",  
                                ifelse(grepl("Fall", data$Survey), 
                                       "Fall",
                                       "Winter")))

For each element of data$Survey : First ifelse will check if it contains "Spring" , then assign it to the corresponding item in data$Season , otherwise second ifelse will check if it contains "Summer"... 对于data$Survey每个元素:第一个ifelse将检查它是否包含“ Spring”,然后将其分配给data$Season的相应项,否则,第二个ifelse将检查它是否包含“ Summer” ...

We can use base R to do this 我们可以使用base Rbase R

data$Season <-  regmatches(data$Survey, regexpr("\\b(Spring|Survey|Fall)\\b", data$Survey))
data$Season
#[1] "Spring" "Spring" "Fall"   "Fall"   "Spring" "Spring" "Fall"   "Spring" "Fall"   "Spring" "Spring"
#[12] "Fall"   "Spring" "Fall"  

data 数据

data <- data.frame(Survey = sample(c("it's Spring yay",
                                 "it's Summer yay",
                                 "it's Fall yay"),
                        20, replace = TRUE))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM