为了整理数据集的一部分,我需要将一列分成几列。这些数据采用类似于以下的形式:
set.seed(2133)
df <- data.frame(a = paste(sample(1:9, 5, replace=T), sample(c("", "%2", "%3"), 5, replace=T), sample(c("", "%3", "%4"), 5, replace=T), sep=""))
df
a
1 6
2 2%3%4
3 6%2
4 3%2
5 5%2%4
Tidyr 的单独函数无法完成这项工作,我最好的想法是一系列 ifelse 语句,如下所示:
df$One <- ifelse(grepl("1", df$a) == T, 1, 0)
df$Two <- ifelse(grepl("2", df$a) == T, 1, 0)
a One Two
1 6 0 0
2 2%3%4 0 1
3 6%2 0 1
4 3%2 0 1
5 5%2%4 0 1
进行这种整理的最佳方法是什么。我敢肯定,许多使用 Open Data Kit (ODK) 进行数据收集的人都会遇到这种情况。