我目前正试图让第一次主题选择蓝色提示进入R中的NaN。如何替换组中第一次出现的值(主题组)与NaN?我试着做以下事情:
replacefirsts<-function(x)
{
dataless[match(unique(dataless$choice==1),dataless$choice),]==NaN;
}
data=tapply(data$sID,list(data$sID),replacefirsts)
当我这样做时,新数据集只有NaN值而不是其余行。
目前我的数据如下:
sID choice
1 2
1 1
1 3
1 1
1 1
2 1
2 2
2 2
2 3
2 3
3 3
3 1
3 2
3 2
3 2
我想要的是:(组内第一次出现的选择1(sID)是NaN:
sID choice
1 2
1 NaN
1 3
1 1
1 1
2 NaN
2 2
2 1
2 3
2 3
3 3
3 NaN
3 2
3 2
3 2
答案 0 :(得分:2)
以下是基础R的方法,
with(df, ave(choice, sID, FUN = function(i) replace(i, which(i == 1)[1], NaN)))
#[1] 2 NaN 3 1 1 NaN 2 2 3 3 3 NaN 2 2 2
答案 1 :(得分:1)
这是使用group_by
dat <- data.frame(sID = rep(1:3, each=3), choice = c(1,2,1,1,2,3,3,1,1))
dat %>%
group_by(sID) %>%
mutate(choice2 = ifelse((choice == 1 & !duplicated(choice == 1)), NaN, choice))
Source: local data frame [9 x 3]
Groups: sID [3]
sID choice choice2
<int> <dbl> <dbl>
1 1 1 NaN
2 1 2 2
3 1 1 1
4 2 1 NaN
5 2 2 2
6 2 3 3
7 3 3 3
8 3 1 NaN
9 3 1 1
答案 2 :(得分:1)
以下是data.table
library(data.table)
setDT(df)[df[, .I[seq_len(.N) == 1 & choice == 1],.(choice, sID)]$V1, choice := NaN][]
# sID choice
# 1: 1 2
# 2: 1 NaN
# 3: 1 3
# 4: 1 1
# 5: 1 1
# 6: 2 NaN
# 7: 2 2
# 8: 2 2
# 9: 2 3
#10: 2 3
#11: 3 3
#12: 3 NaN
#13: 3 2
#14: 3 2
#15: 3 2
或base R
with(df, NaN^(!duplicated(df) & choice == 1)*choice)
#[1] 2 NaN 3 1 1 NaN 2 2 3 3 3 NaN 2 2 2