Synopsys
我已经有了一个使用"for“循环的解决方案,但我想知道是否有一些优雅的方法,可能使用dplyr或基R。
现有数据
2数据帧。两者都有确切的非唯一标记的确切顺序;除了eeg有不可预测的零数。行为数据集"behav“具有与标记相关的刺激数"stim”。(实际上,我在每个dataframe中都有更多的列,但为了简单起见不包括它们)
behav = data.frame(
marker = c(1,2,3,1,2,3,7,13),
stim = c(168,168,168,78,78,78,23,55)
)
eeg = data.frame(
marker = c(0,0,1,0,0,2,0,0,3,0,0,1,0,0,2,0,0,3,0,7,0,13)
)需求
我需要给eeg数据贴上行为刺激号的标签。保存行顺序是一个必须具备的条件。
结果应该如下所示:
eeg2 = data.frame(
marker = c(0,0,1,0,0,2,0,0,3,0,0,1,0,0,2,0,0,3,0,7,0,13),
stim = c(0,0,168,0,0,168,0,0,168,0,0,78,0,0,78,0,0,78,0,23,0,55)
)我的解决方案
这样做的工作和性能是不错的大型脑电数据集。
eeg2=eeg;
eeg2$stim=NA;
lrow=1;
for(i in 1:nrow(behav)){
behav_marker = behav[i, "marker"];
for(j in lrow:nrow(eeg)){
eeg_marker = eeg[j, "marker"];
if(eeg_marker == behav_marker){
eeg2[j,'stim'] = behav[i,'stim'];
lrow = j+1;
break;
}
}
}使用dplyr或基R函数的更优雅的方法可以改进我的问题解决方案吗?
发布于 2018-05-28 13:03:59
如果问题仅来自带有零的行,而其余的则是完全相同的顺序,则可以通过将stim列定义为仅为零来解决问题,然后用对应的behav值填充marker的非零值。
eeg$stim <- 0
eeg$stim[eeg$marker!=0] <- behav$stim
eeg
# marker stim
# 1 0 0
# 2 0 0
# 3 1 168
# 4 0 0
# 5 0 0
# 6 2 168
# 7 0 0
# 8 0 0
# 9 3 168
# 10 0 0
# 11 0 0
# 12 1 78
# 13 0 0
# 14 0 0
# 15 2 78
# 16 0 0
# 17 0 0
# 18 3 78
# 19 0 0
# 20 7 23
# 21 0 0
# 22 13 55发布于 2018-05-28 13:41:37
为了完整起见,我们已经提供了一个base解决方案,这里是我如何使用dplyr的方法
使用dplyr::left_join()合并eeg和behav,然后用dplyr::mutate()填充NAs中的0
eeg2 <- dplyr::left_join(eeg, behav, by = c("marker"))
eeg2 <- dplyr::mutate(eeg2, stim = dplyr::if_else(is.na(stim), 0, stim))结果:
marker stim
1 0 0
2 0 0
3 1 168
4 1 78
5 0 0
6 0 0
7 2 168
8 2 78
9 0 0
10 0 0
11 3 168
12 3 78
13 0 0
14 0 0
15 1 168
16 1 78
17 0 0
18 0 0
19 2 168
20 2 78
21 0 0
22 0 0
23 3 168
24 3 78
25 0 0
26 7 23
27 0 0
28 13 55不过,在这个特殊的例子中,我建议使用来自magrittr的管道(magrittr)(它增加了一些开销,但使代码更短一些,并且流得更好):
eeg2 <- dplyr::left_join(eeg, behav, by = c("marker")) %>%
dplyr::mutate(stim = dplyr::if_else(is.na(stim), 0, stim))https://stackoverflow.com/questions/50566856
复制相似问题