0

We have a survey that asks for 'select all that apply' so the result is a string inside quotes with the values separated by commas. i.e. "red, black,green"

There are other question about income so I have a factor with 'low, medium, high'

I want to be able to answer questions: What percent selected 'Red', then group that by income.

I can split the string with '''df4 <- c("black,silver,green")''' I can create a data frame with a timestamp and the split string with '''t2 <- as.data.frame(c(df2[2],l2))'''

I am not able to understand how to do this for all rows at one time.

Here is a DPUT of the input:

    structure(list(RespData = structure(1:2, .Label = c("1/20/2020", 
    "1/21/2020"), class = "factor"), CarColor =             c("red,blue,green,yellow", 
    "black,silver,green")), row.names = c(NA, -2L), class =     "data.frame")

and here is a DPUT of the desired output:

    structure(list(RespData = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 
2L), .Label = c("1/20/2020", "1/21/2020"), class = "factor"), 
    Cars = structure(c(3L, 1L, 2L, 4L, 5L, 6L, 2L), .Label = c("blue", 
    "green", "red", "yellow", "black", "silver"), class = "factor")), row.names = c(NA, 
-7L), class = "data.frame")

Example of Function:

MySplitFunc <- function(ListIn) {
# build an empty data frame and set the column names
   x1.all <- ListIn[0,]
  names(x1.all) <- c("ResponseTime", "Descriptive")
  # for each row build the data and combine to growing list
  for(x in 1:nrow(ListIn)) {
    #print(x)
    r1 <- ListIn[x,1]
    c1 <- strsplit(ListIn[x,2],",")
    x1 <- as.data.frame(c(r1,c1))
  # set the names and combine to all
    names(x1) <- c("ResponseTime", "Descriptive")
    x1.all <- rbind(x1.all,x1)

  }
  # strip the whitespace
  x1.all <- data.frame(lapply(x1.all, trimws), stringsAsFactors = TRUE)

  return(x1.all)
}
Mike B.
  • 1
  • 2

0 Answers0