mardi 18 juin 2019

R - How to fix function with if statement and multiple conditions (factor variables)

I have a df with two relevant columns with 1.words of different lengths and another with 2.labels for syllables, both are factor variables. Now in a third column (3. structure) I want to add information about the components of the syllable (Vowel or Consonant). To do this I use the word and the label of the syllable as conditions.

(word <- "dog", "parent", "extraordinary")
(labels <- "1", "2", "3","Final", "Mono")
(df <- data.frame(word,labels))

I have used very similar code before and it worked but now it doesn't anymore. I recently uploaded R (3.6.0) and can't figure out where the issue lies. I also updated all the packages I thought would be relevant for this but still no luck. I only get a column with only CV in it. My df is also much bigger although I don't think that's the issue.

Classes ‘rowwise_df’, ‘tbl_df’, ‘tbl’ and 'data.frame': 4458 obs. of  27 variables: 

This is an excerpt of how my code looks like:

getStructure <- function(word, labels) {
  if (str_detect(word, 'extraordinary') & labels == '2') {
    return ('CCV')  
  } else {
    return("CV")
  }
  }

df <- df %>%
  rowwise() %>% 
  mutate(structure =getStructure(word, labels))

example of what I need:

|word  | labels | structure
---------------------------
|dog   | Mono   | CVC 
|parent| 1      | CV
|parent| Final  | CVC


I would like to use a function and specify each word and syllable when necessary. After that the remaining is all CV.

However, I only get one new column with CV in all rows and this

Warning message:
In if (str_detect(word, "dog") & labels == "1") { :
  the condition has length > 1 and only the first element will be used

Aucun commentaire:

Enregistrer un commentaire