简体   繁体   English

我可以将列表中的数据添加到数据框的列吗

[英]Can I add data from a list to the columns of a dataframe

I've written code to extract data from a dataframe in a for loop and added it to a list.我已经编写了代码来从 for 循环中的数据帧中提取数据并将其添加到列表中。 Like this:像这样:

  list_vraag1 <- list()        
  for (i in seq(1,nrow(questionanswer),16)){        
    if (questionanswer$answer[i] == 1){        
     antwoord1 <- "Ja"
      } else if (questionanswer$answer[i+1] == 1){        
    antwoord1 <- "Nee"
      } else{        
       antwoord1 <- NA
      }          
      df <- append(list_vraag1, antwoord1)
    }

It gives a correct list (I created 6 of those lists for the six different questions), now I've tried to add them to a new dataframe where I need to have 6 different columns and under each column there has to be one whole list.它给出了一个正确的列表(我为六个不同的问题创建了其中的 6 个列表),现在我尝试将它们添加到一个新的数据框中,在那里我需要有 6 个不同的列,并且在每一列下必须有一个完整的列表. Is this possible?这可能吗? When I tried this, the whole list came on the column name.当我尝试这个时,整个列表都出现在列名上。 Does someone has a solution for this?有人对此有解决方案吗?

It's not entirely clear what you are after here.目前还不完全清楚你在这里追求什么。 Taking every 16th row is a bit puzzling to me but I am sure it has utility in your application.每 16 行取一次对我来说有点令人费解,但我相信它在您的应用程序中有用。 I am assuming that questionanswer is either a vector or a tibble (data frame) containing a 1 or a 0 (or anything not equal to 1).我假设questionanswer是包含 1 或 0(或任何不等于 1 的任何值)的向量或 tibble(数据框)。 Under those assumptions:在这些假设下:

library(dplyr)
library(tibble)

questionanswer <- tibble(
  answer = sample(c(0, 1), replace = TRUE, size = 100)
)

out <- questionanswer %>%
  mutate(antwoord1 = case_when(answer == 1 ~ "Ja",
                               lead(answer, 1) == 1 ~ "Nee",
                               TRUE ~ "NA")) %>%
  slice(which(row_number() %% 16 == 1)) # slices every 16th row

Ok, out is not a list but a tibble.好吧, out不是一个列表,而是一个 tibble。 But we could easily coerce this to a list.但是我们可以轻松地将其强制为列表。 lapply would probably not be useful here as you are using a lead function ( (questionanswer$answer[i+1] looks at the next element). lapply在这里可能没有用,因为您使用的是lead函数( (questionanswer$answer[i+1]查看下一个元素)。

With a for loop this could look like this:使用 for 循环,这可能如下所示:

list_vraag1 <- list()        
index <- seq(1,nrow(questionanswer), by = 16)
for (i in seq_along(index)){   
  if (questionanswer$answer[index[i]] == 1){        
    antwoord1 <- "Ja"
  } else if (questionanswer$answer[index[i] + 1] == 1){        
    antwoord1 <- "Nee"
  } else{        
    antwoord1 <- NA
  }          
  list_vraag1[[i]] <- antwoord1
}

Which will return a list.这将返回一个列表。 Is this helpful?这有帮助吗?

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

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