我有一组调查回复,受访者可以选择零个或多个选项来回答“你喜欢哪种水果?”这个问题。还有一个填写答案的空间。在结果电子表格中,每个人的回答都在一个单元格中,不同类型的水果用逗号分隔,如下所示:
(df <- data.frame(id = c("A", "B", "C", "D", "E"),
data = c("oranges, apples, peaches, cherries, pineapples, strawberries",
"oranges, peaches, pears",
"pears, nectarines, cherries (bing, rainier)",
"apples, peaches, nectarines",
""),
stringsAsFactors = FALSE))
# id data
# 1 A oranges, apples, peaches, cherries, pineapples, strawberries
# 2 B oranges, peaches, pears
# 3 C pears, nectarines, cherries (bing, rainier)
# 4 D apples, peaches, nectarines
# 5 E
我想要做的是将响应拆分成一个长格式的表格,我使用底部的代码几乎已经完成了。但是,一些受访者在他们的填写回复中包含逗号,我不想在逗号上拆分他们的答案。我知道所有最初的多项选择选项是什么;我怎样才能只拆分这些答案,而使写入(带逗号)完好无损?我想最终得到这样的数据框:
id data
1 A oranges
2 A apples
3 A peaches
4 A cherries, pineapples, strawberries
5 B oranges
6 B peaches
7 B pears
8 C pears
9 C nectarines
10 C cherries (bing, rainier)
11 D apples
12 D peaches
13 D nectarines
多项选择选项是:
mc_answers <- c("oranges", "plums", "apples", "peaches", "pears", "nectarines")
到目前为止,我已经完成的是:
# use strsplit to create a list of the types of fruit each person likes
datalist <- strsplit(df$data, ", ")
names(datalist) <- df$id
# remove zero-length list elements (person E doesn't like any fruit)
datalist <- Filter(length, datalist)
# convert list elements to data frames
datalist_dfs <- lapply(datalist, data.frame, stringsAsFactors = FALSE)
datalist_dfs <- lapply(datalist_dfs, setNames, "data") # name each column 'data'
# add id column to each data frame
data_long <- mapply(function(x, y) "[<-"(x, "id", value = y), datalist_dfs,
names(datalist_dfs), SIMPLIFY = FALSE)
# combine into one big data frame
(data_per_person <- do.call('rbind', data_long))
# data id
# A.1 oranges A
# A.2 apples A
# A.3 peaches A
# A.4 cherries A # should
# A.5 pineapples A # be one
# A.6 strawberries A # entry
# B.1 oranges B
# B.2 peaches B
# B.3 pears B
# C.1 pears C
# C.2 nectarines C
# C.3 cherries (bing C # should be
# C.4 rainier) C # one entry
# D.1 apples D
# D.2 peaches D
# D.3 nectarines D
一个人可以选择多少水果没有规则,但如果有一个写下的答案,它总是最后一个。