I've written code to extract data from a dataframe in a for loop and added it to a list. 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. 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. 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). 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. 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).
With a for loop this could look like this:
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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.