【发布时间】:2016-09-08 03:59:44
【问题描述】:
我在尝试使用 ifelse 创建新列时遇到问题。非常相似的问题是这个dplyr error: strange issue when combining group_by, mutate and ifelse. Is it a bug?
set.seed(101)
time =sort(runif(10,0,10))
group=rep(c(1,2),each=5)
az=c(sort(runif(5,-1,1),decreasing = T),sort(runif(5,-1,0.2),decreasing = T))
df <- data.frame(time,az,group)
# time az group
#1 0.4382482 0.86326886 1
#2 2.4985572 0.75959146 1
#3 3.0005483 0.46394519 1
#4 3.3346714 0.41374948 1
#5 3.7219838 -0.08975881 1
#6 5.4582855 -0.01547669 2
#7 5.8486663 -0.29161632 2
#8 6.2201196 -0.50599980 2
#9 6.5769040 -0.73105782 2
#10 7.0968402 -0.95366733 2
在df 中,我正在尝试条件变异clas 列。但是,由于sw_time 内部有NA,因此所有clas 列也变为NA,其中group 1 通常应该是nrm。
df1 <- df%>%
group_by(group)%>%
mutate(sw_time=abs(time[which(az<=0.8)[1]]-time[which(az>0)[1]]))%>%
mutate(clas=as.numeric(ifelse(sw_time<3,"nrm","abn")))
Source: local data frame [10 x 5]
Groups: group [2]
time az group sw_time clas
(dbl) (dbl) (dbl) (dbl) (dbl)
1 0.4382482 0.86326886 1 2.060309 NA
2 2.4985572 0.75959146 1 2.060309 NA
3 3.0005483 0.46394519 1 2.060309 NA
4 3.3346714 0.41374948 1 2.060309 NA
5 3.7219838 -0.08975881 1 2.060309 NA
6 5.4582855 -0.01547669 2 NA NA
7 5.8486663 -0.29161632 2 NA NA
8 6.2201196 -0.50599980 2 NA NA
9 6.5769040 -0.73105782 2 NA NA
10 7.0968402 -0.95366733 2 NA NA
提前感谢您的行动!
【问题讨论】:
-
您将字符强制转换为数字。它肯定会导致NA。也许你需要
clas = as.numeric(factor(ifelse(... -
@akrun 是的,我刚试过,但现在
group 1clas变成 1 而不是nrm -
在这种情况下,您只需删除
as.numeric。