Итеративно добавлять значения в список с помощью индексации в цикле for - PullRequest
0 голосов
/ 06 мая 2018

Это следующий вопрос к этому вопросу: Добавьте два целых числа к каждому элементу списка в цикле for

Я бы хотел итеративно добавлять значения в список очень заданным образом: У меня есть этот список:

> dput(head(word.vectors.table, 2))
structure(list(`Gina Haley` = structure(c(1L, 3L, 2L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 
1L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 1L, 7L, 1L, 1L, 
1L, 1L, 3L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 3L, 2L, 1L, 1L, 
1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 1L, 2L, 
1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 4L, 
1L), .Dim = 134L, .Dimnames = structure(list(c("after", "album", 
"american", "angeles", "angelesshe", "appeared", "april", "around", 
"arranging", "become", "birthdayin", "bridge", "called", "carry", 
"catch", "ceremony", "charts", "chelo", "child", "christi", "clock", 
"closely", "colaiuta", "comets", "concert", "continues", "corpus", 
"costa", "country", "dallas", "daniel", "decided", "dedicate", 
"during", "event", "falcao", "famous", "father", "fathers", "field", 
"finally", "first", "followshe", "formed", "gallardo", "georgina", 
"ginas", "grogan", "group", "guitarist", "haley", "haleys", "harlingen", 
"heath", "hollywood", "horton", "houston", "identity", "important", 
"included", "inductees", "induction", "inspired", "intended", 
"japan", "jobim", "joint", "landed", "later", "legacy", "linda", 
"making", "managed", "march", "marriage", "martha", "members", 
"mexico", "michael", "moved", "movies", "music", "musical", "musician", 
"original", "other", "paulinho", "perform", "performed", "piano", 
"pioneer", "position", "preparing", "producer", "published", 
"reaching", "recording", "released", "reverend", "richard", "rockabilly", 
"rudolph", "sales", "selftaught", "selftitled", "sembello", "silva", 
"songs", "songwriter", "sound", "south", "stalling", "start", 
"state", "television", "texas", "texason", "these", "through", 
"tracks", "trained", "traveled", "txshe", "vincent", "viper", 
"waveduring", "which", "whose", "worked", "world", "would", "writing", 
"years", "youngest")), .Names = ""), class = "table"), `Kevin Yates (politician)` = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 
1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 4L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 1L, 1L, 4L, 1L, 1L, 1L, 2L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 5L, 1L, 1L), .Dim = 63L, .Dimnames = structure(list(
    c("along", "assembly", "bargaining", "before", "beyond", 
    "byelection", "cabinet", "canadian", "carmichael", "chief", 
    "community", "council", "declined", "deputy", "dewdney", 
    "disability", "elected", "employed", "executive", "explaining", 
    "february", "first", "government", "house", "issues", "kevin", 
    "leader", "leaderon", "lorne", "media", "minister", "moved", 
    "named", "negotiator", "opposition", "party", "personal", 
    "politician", "position", "premier", "provincial", "public", 
    "reasons", "reelected", "regina", "resources", "result", 
    "returned", "safety", "september", "served", "service", "shuffle", 
    "social", "sources", "speculated", "stepped", "stepping", 
    "which", "worker", "yates", "years", "yearsyates")), .Names = ""), class = "table")), .Names = c("Gina Haley", 
"Kevin Yates (politician)"))

У меня также есть пары индексов, где первая пара (x) обозначает номер компонента в списке, а вторая пара обозначает y значение внутри x компонента.

> dput(head(index, 20))
list(c(1L, 1L), 1:2, c(1L, 3L), c(1L, 4L), c(1L, 6L), c(1L, 7L
), c(1L, 8L), c(1L, 10L), c(1L, 12L), c(1L, 13L), c(1L, 14L), 
    c(1L, 16L), c(1L, 17L), c(1L, 19L), c(1L, 22L), c(1L, 25L
    ), c(1L, 26L), c(1L, 28L), c(1L, 29L), c(1L, 30L))

Я хотел бы создать пустой список (new.table) и использовать цикл for для вставки значений в new.table

Вот важная часть:

Я хочу использовать список индексов (index) для извлечения значений из word.vectors.table и помещения этих значений в new.table, чтобы можно было поместить все «извлеченные» значения в одном и том же компоненте word.vectors.table в тот же компонент в new.table.

Вот что я пробовал:

new.table <- list()
for (ii in seq(index)) {
  new.table[[index[[ii]][1]]] <- c(new.table[[index[[ii]][1]]], word.vectors.table[[index[[ii]][1]]][index[[ii]][2]])
}

РЕДАКТИРОВАТЬ: Согласно комментариям Мелиссы, я добавил желаемый результат (test):

> dput(test)
list(structure(c(1L, 3L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Dim = 20L, .Dimnames = structure(list(
    c("after", "album", "american", "angeles", "angelesshe", 
    "appeared", "april", "around", "arranging", "become", "birthdayin", 
    "bridge", "called", "carry", "catch", "ceremony", "charts", 
    "chelo", "child", "christi")), .Names = ""), class = "table"), 
    structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 
    1L, 1L, 1L), .Dim = 30L, .Dimnames = structure(list(c("along", 
    "assembly", "bargaining", "before", "beyond", "byelection", 
    "cabinet", "canadian", "carmichael", "chief", "community", 
    "council", "declined", "deputy", "dewdney", "disability", 
    "elected", "employed", "executive", "explaining", "february", 
    "first", "government", "house", "issues", "kevin", "leader", 
    "leaderon", "lorne", "media")), .Names = ""), class = "table"), 
    structure(c(1L, 2L, 1L, 1L, 3L, 1L, 14L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 3L, 3L, 1L, 1L, 1L, 
    2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 3L), .Dim = 40L, .Dimnames = structure(list(
        c("ability", "about", "affect", "against", "agents", 
        "agerelated", "aging", "alistair", "alzheimers", "animals", 
        "appeared", "applied", "applies", "associated", "attended", 
        "audiences", "award", "balance", "basel", "became", "behavioral", 
        "between", "biology", "braidhurst", "breakdown", "brown", 
        "called", "cancerthe", "capable", "career", "cells", 
        "cellular", "center", "certain", "checkpoint", "chemical", 
        "chemicals", "closely", "colorado", "compounds")), .Names = ""), class = "table"))

1 Ответ

0 голосов
/ 06 мая 2018

Вот решение с использованием пакета tidyverse пакетов. Я бы начал с изменения формата вашего индексного вектора:

index <- do.call(rbind, index) %>%
  as_data_frame()    

Следующий шаг - разделить индексы по первому столбцу (теперь он называется V1) - это определит, какой компонент word.vectors.table мы рассмотрим. Наконец, функция map2 позволяет нам взять элементы двух списков и вставить их в функцию (например, первый элемент list1 и 1-й элемент list2; 2-й элемент list1 и 2-й элемент list2 и т. Д.

result <- result <- index %>%
  split(., .$V1) %>%
  map2(., word.vectors.table[index$V1 %>% unique() %>% sort()], ~ .y[.x$V2]) 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...