180 вложенных условий в отдельный файл для создания новой переменной id для каждой строки в моем фрейме данных - PullRequest
0 голосов
/ 12 июня 2019

Мне нужно определить 180 коротких предложений, написанных участниками эксперимента, и сопоставить каждому предложению порядковый номер в новом столбце. У меня 180 условий в отдельном файле. Все тексты на иврите, но я прилагаю примеры на английском языке, которые можно понять.

Я добавляю пример из семи строк из экспериментальных данных из 180 строк. Есть 181 разных условий. У каждого есть свой серийный номер. Поэтому я также добавляю небольшой пример с 6 условиями, которые соответствуют данным этого участника:

data_participant <- data.frame("text" =  c("I put a binder on a high shelf", 
                                           "My friend and me are eating chocolate", 
                                           "I wake up with  superhero powers", 
                                           "Low wooden table with cubes", 
                                           "The most handsome man in camopas invites me out", 
                                           "My mother tells me she loves me and protects me", 
                                           "My laptop drops and breaks"), 
                               "trial" = (1:7) )  

data_condition <- data.frame("condition_a" = c("wooden table"  , "eating" , "loves", 
                                               "binder", "handsome", "superhero"), 
                             "condition_b" = c("cubes",  "chocolate", "protects me", 
                                               "shelf","campos", "powers"), 
                             "condition_c" = c("0", "0", "0", "0", "me out", "0"),
                             "i.d." = (1:6) )

Я решил использовать функцию ifelse и стратегию вложенных условий и написать 181 строку кода. Для каждого условия одна строка. Это также громоздко, потому что требует перехода с английского на иврит. Но после 30 строк я начал получать сообщение об ошибке:

переполнение контекстного стека

Снимок экрана с ошибкой в ​​строке 147 означает, что после 33 условий.

В примере не более 3 ключевых слов на условие, но в полных данных есть условия с 5 или 6 ключевыми словами. (Причиной этого является разнообразие словесных формулировок участников). Следовательно, исходная таблица условий имеет 7 столбцов: on для i.d. нет. а остальные - это идентификаторы слов для того же условия с оператором "или".

data <- mutate(data, script_id = ifelse((grepl( "wooden table" ,data$imagery))|(grepl( "cubes" ,data$imagery))
                                        ,"1",
                                        ifelse((grepl( "eating" ,data$imagery))|(grepl( "chocolate" ,data$imagery))
                                               ,"2",
                                               ifelse((grepl( "loves" ,data$imagery))|(grepl( "protect me" ,data$imagery))
                                                      ,"3", 

                                                      ifelse((grepl( "binder" ,data$imagery))|(grepl( "shelf" ,data$imagery))  
                                                             ,"4", 

                                                             ifelse(  (grepl("handsome"  ,data$imagery)) |(grepl( "campus" ,data$imagery) )|(grepl( "me out" ,data$imagery)) 
                                                                      ,"5",        

                                                                      ifelse((grepl("superhero", data$imagery)) | (grepl( "powers"  , data$imagery   ))
                                                                             ,"6",

                                                                             "181")))))))

# I expect the output will be new  column in the participant data frame 
# with the corresponding ID number for each text.
# I managed to get it when I made 33 conditions rows. And then I started 
# to get an error message contextstack overflow.

final_output <- data.frame("text" =  c("I put a binder on a high shelf", "My friend and me are eating chocolate", 
                                       "I wake up with  superhero powers", "Low wooden table with cubes", 
                                       "The most handsome man in camopas invites me out", 
                                       "My mother tells me she loves me and protects me", 
                                       "My laptop drops and breaks"), 
                           "trial" = (1:7), 
                           "i.d." = c(4, 2, 6, 1, 5, 3, 181) )

1 Ответ

0 голосов
/ 13 июня 2019

Вот подход, использующий fuzzymatch::regex_left_join.

data_condition_long <- data_condition %>%
  gather(col, text_match, -`i.d.`) %>%
  filter(text_match != 0) %>%
  arrange(`i.d.`)

data_participant %>%
  fuzzyjoin::regex_left_join(data_condition_long %>% select(-col), 
                             by = c("text" = "text_match")) %>%
  mutate(`i.d.` = if_else(is.na(`i.d.`), 181L, `i.d.`)) %>%
  # if `i.d.` is doubles instead of integers, use this:
  # mutate(`i.d.` = if_else(is.na(`i.d.`), 181, `i.d.`)) %>%
  group_by(trial) %>%
  slice(1) %>%
  ungroup() %>%
  select(-text_match)

# A tibble: 7 x 3
  text                                            trial  i.d.
  <fct>                                           <int> <int>
1 I put a binder on a high shelf                      1     4
2 My friend and me are eating chocolate               2     2
3 I wake up with  superhero powers                    3     6
4 Low wooden table with cubes                         4     1
5 The most handsome man in camopas invites me out     5     5
6 My mother tells me she loves me and protects me     6     3
7 My laptop drops and breaks                          7   181
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...