根据天数重新排列和合并序列数据集
Rearrange and merge a dataset of sequences based on days
我正在处理一个数据集,人们必须在其中填写两天的活动。
问卷 1 旨在收集第 1 天的数据,而问卷 2 则用于第 2 天的数据。
但有些受访者在问卷 1 中填写了第 2 天,在问卷 2 中填写了第 1 天。
所以基本上我想要的是重新排列和合并(或合并和重新排列)数据,以便让每个受访者在第 1 天和第 2 天之后。
seq1 = as.data.frame( rbind(c(1, 1, 1, 'a', 'a', 'b', 'c'),
c(2, 1, 1, 'a', 'a', 'b', 'd'),
c(3, 1, 2, 'c', 'd', 'b', 'a'),
c(4, 1, 2, 'c', 'a', 'b', 'e')))
colnames(seq1) <- c('id', 'quest', 'day', paste('act',1:4))
seq2 = as.data.frame( rbind(c(1, 2, 2, 'a', 'a', 'b', 'd'),
c(2, 2, 2, 'c', 'a', 'b', 'c'),
c(3, 2, 1, 'a', 'd', 'b', 'c'),
c(4, 2, 1, 'd', 'a', 'b', 'c') ))
colnames(seq2) <- c('id', 'quest', 'day', paste('act',1:4))
# seq1
id quest day act 1 act 2 act 3 act 4
1 1 1 1 a a b c
2 2 1 1 a a b d
3 3 1 2 c d b a # Mistake here
4 4 1 2 c a b e # Mistake here
# seq 2
id quest day act 1 act 2 act 3 act 4
1 1 2 2 a a b d
2 2 2 2 c a b c
3 3 2 1 a d b c # Mistake here
4 4 2 1 d a b c # Mistake here
所以我想合并我的数据,以便将第 1 天和第 2 天放在一起。
merge(seq1, seq2, by = 'id', suffixes = c('_day1', '_day2'))
我想要一个看起来像这样但正确重新排列日期的数据集。
id quest_day1 day_day1 act 1_day1 act 2_day1 act 3_day1 act 4_day1 quest_day2 day_day2 act 1_day2 act 2_day2 act 3_day2 act 4_day2
1 1 1 1 a a b c 2 2 a a b d
2 2 1 1 a a b d 2 2 c a b c
3 3 1 2 c d b a 2 1 a d b c
4 4 1 2 c a b e 2 1 d a b c
我确信 dplyr 有一个简单的解决方案来重新排列数据帧。
有什么解决办法吗?
您不需要 dplyr
,并且 merge
不是这项工作的正确工具。只需 rbind
您的数据集,然后对它们进行排序。
all.data <- rbind(seq1, seq2)
all.data <- all.data[order(all.data$day),]
我正在处理一个数据集,人们必须在其中填写两天的活动。
问卷 1 旨在收集第 1 天的数据,而问卷 2 则用于第 2 天的数据。 但有些受访者在问卷 1 中填写了第 2 天,在问卷 2 中填写了第 1 天。
所以基本上我想要的是重新排列和合并(或合并和重新排列)数据,以便让每个受访者在第 1 天和第 2 天之后。
seq1 = as.data.frame( rbind(c(1, 1, 1, 'a', 'a', 'b', 'c'),
c(2, 1, 1, 'a', 'a', 'b', 'd'),
c(3, 1, 2, 'c', 'd', 'b', 'a'),
c(4, 1, 2, 'c', 'a', 'b', 'e')))
colnames(seq1) <- c('id', 'quest', 'day', paste('act',1:4))
seq2 = as.data.frame( rbind(c(1, 2, 2, 'a', 'a', 'b', 'd'),
c(2, 2, 2, 'c', 'a', 'b', 'c'),
c(3, 2, 1, 'a', 'd', 'b', 'c'),
c(4, 2, 1, 'd', 'a', 'b', 'c') ))
colnames(seq2) <- c('id', 'quest', 'day', paste('act',1:4))
# seq1
id quest day act 1 act 2 act 3 act 4
1 1 1 1 a a b c
2 2 1 1 a a b d
3 3 1 2 c d b a # Mistake here
4 4 1 2 c a b e # Mistake here
# seq 2
id quest day act 1 act 2 act 3 act 4
1 1 2 2 a a b d
2 2 2 2 c a b c
3 3 2 1 a d b c # Mistake here
4 4 2 1 d a b c # Mistake here
所以我想合并我的数据,以便将第 1 天和第 2 天放在一起。
merge(seq1, seq2, by = 'id', suffixes = c('_day1', '_day2'))
我想要一个看起来像这样但正确重新排列日期的数据集。
id quest_day1 day_day1 act 1_day1 act 2_day1 act 3_day1 act 4_day1 quest_day2 day_day2 act 1_day2 act 2_day2 act 3_day2 act 4_day2
1 1 1 1 a a b c 2 2 a a b d
2 2 1 1 a a b d 2 2 c a b c
3 3 1 2 c d b a 2 1 a d b c
4 4 1 2 c a b e 2 1 d a b c
我确信 dplyr 有一个简单的解决方案来重新排列数据帧。
有什么解决办法吗?
您不需要 dplyr
,并且 merge
不是这项工作的正确工具。只需 rbind
您的数据集,然后对它们进行排序。
all.data <- rbind(seq1, seq2)
all.data <- all.data[order(all.data$day),]