How do I index and save the strings in adjacent rows in a df in R?

Viewed 43

I have limited r knowledge and would like to run such a task in a big data frame: Data frame consists of binary answers of 1 and 2, and on the adjacent row the reasoning why the person chose that answer:

A_answer1 reasoning1 B_answer2 reasoning2 A_answer3 reasoning3
1 "some statement" 2 "some reasoning" 1 "yes"
2 "another statement" 1 "some sentence" 1 "because of x"

As the first task I want to have 2 df of strings, if the answer is one, saving the adjacent string to a df. if the answer is 2, saving the string to another df. In the end I want to have a df1:

"some statement" "yes" "some sentence" "because of x"

and df2:

"some reasoning" "another statement"

I managed to do the first one with this loop:

drive <- list() #create an empty list
yield <- list()
c <- 0

for(i in seq(3,ncol(df),2)) {
  c<- c+1
  temp <- df[i+1]
  drive[[c]] <- temp[df[i]==1]
  yield[[c]] <- temp[df[i]==2]
}


lapply(drive, function(x) write.table( data.frame(x), 'drive.csv'  , append= T, sep=',' ))
lapply(yield, function(x) write.table( data.frame(x), 'yield.csv'  , append= T, sep=',' ))

As the second task I would like to have 2 df of strings per condition. Answer 1 and answer 3 belong to the same condition "A". I would like to extract strings from condition A per answer group 1 and 2. so in this case what I want is df1_A: "same statement" "yes" "because of x"

and df2_A: "another statement"

I appreciate your help!

1 Answers

We can stack your data up in a long format so that it is easier to work with:

library(dplyr)

# identify answer and reason columns
answer_cols = grep("answer", names(df), value = T)
reason_cols = grep("reason", names(df), value = T)

# make long data
long_df = data.frame(
  answers = unlist(df[answer_cols]),
  reasons = unlist(df[reason_cols])
)
#            answers           reasons
# A_answer11       1    some statement
# A_answer12       2 another statement
# B_answer21       2    some reasoning
# B_answer22       1     some sentence
# A_answer31       1               yes
# A_answer32       1      because of x

# filter the long data to get your results
long_df %>% filter(answers == 1)
#            answers        reasons
# A_answer11       1 some statement
# B_answer22       1  some sentence
# A_answer31       1            yes
# A_answer32       1   because of x

long_df %>% filter(answers == 2)
#            answers           reasons
# A_answer12       2 another statement
# B_answer21       2    some reasoning
Related