【发布时间】:2021-01-06 16:11:14
【问题描述】:
我有一个包含两列 Q10_headache_tibble 的数据框:
structure(list(df_questionaire.headaches = c(0L, 2L, 2L, 2L,
0L, 0L, 0L, 0L, 2L, 0L, 2L, 2L, 0L, 2L, 0L, 2L, 2L, 2L, 2L, 2L,
2L, 0L, 2L, 0L, 2L, 0L, 2L, NA, 2L, 2L, 0L, 2L, 0L, 2L, 2L, 0L,
0L, 0L, 0L, 2L, 0L, 0L, 0L, 0L, 0L, 2L, 2L, 0L, 0L, 0L, 0L, 0L,
0L, 2L, 0L, 2L, 2L, 0L, 0L, 2L, 0L, 0L, 0L, 0L, 2L, 0L, 2L, 0L,
0L, 0L, 2L, 0L, 2L, 0L, 2L, 0L, 0L, 2L, 2L, 0L, 0L, 2L, 2L, 2L,
0L, 0L, 0L, 0L, 2L, 0L, 2L, 0L, 0L, 0L, 0L, 2L, 0L, 2L, 2L, 2L,
2L, 0L, 0L, 0L, 0L, 2L, 0L, 2L, 2L, 0L, 0L, 2L, 0L, 0L, 0L, 2L,
0L, 2L, 2L, 0L, 0L, 2L, 0L, 2L, 2L, 0L, 2L, 2L, 2L, 2L, 0L, 0L,
0L, 0L, 2L, 0L, 0L, 0L, 2L, 0L, 0L, 0L, 0L, 0L, 2L, 0L, 0L, 2L,
2L, 0L, 0L, 0L, 2L, 0L, 0L, 0L, 0L, 0L, 2L, 2L, 0L, 2L, 0L, 0L,
0L, 0L, 2L, 2L, 2L, 2L, 2L, 0L, 2L, 0L, 0L), df_questionaire.headaches_covid = c(0L,
0L, 2L, 2L, 2L, 0L, 0L, 0L, 0L, 2L, 0L, 2L, 0L, 0L, 0L, 0L, 2L,
2L, 2L, 2L, 2L, 0L, 2L, 0L, 2L, 2L, 0L, NA, 2L, 2L, 0L, 0L, 0L,
2L, 2L, 0L, 0L, 0L, 0L, 2L, 0L, 0L, 0L, 0L, 2L, 2L, 0L, 0L, 0L,
0L, 2L, 0L, 0L, 2L, 0L, 2L, 0L, 0L, 2L, 0L, 0L, 0L, 0L, 0L, 2L,
0L, 0L, 774L, 0L, 0L, 0L, 2L, 2L, 774L, 0L, 0L, 0L, 2L, 0L, 2L,
0L, 2L, 0L, 2L, 0L, 0L, 2L, 0L, 2L, 0L, 2L, 0L, 0L, 0L, 0L, 0L,
0L, 2L, 2L, 0L, 2L, 0L, 2L, 2L, 0L, 2L, 0L, 0L, 2L, 0L, 0L, 2L,
2L, 2L, 0L, 2L, 0L, 2L, 0L, 0L, 2L, 2L, 0L, 2L, 0L, 0L, 0L, 2L,
2L, 0L, 0L, 0L, 0L, 0L, 2L, 2L, 0L, 0L, 2L, 0L, 0L, 0L, 0L, 0L,
2L, 0L, 0L, 2L, 2L, 0L, 774L, 0L, 2L, 0L, 0L, 0L, 0L, 0L, 0L,
2L, 0L, 2L, 774L, 0L, 2L, 0L, 0L, 2L, 2L, 2L, 2L, 774L, 0L, 0L,
774L)), row.names = c(NA, -175L), class = c("tbl_df", "tbl",
"data.frame"))
我创建了一个函数,该函数应返回与 nrow(df_headache_tibble) 长度相同的字符向量 (Q10_incidence),该函数基于应用于数据帧的嵌套条件,按行排列。 Q10_incidence[i] 应该是将函数应用到我打算使用 mapply 的 df_headache_tibble[i,1] 和 df_headache_tibble[i,2] 的结果。
incidence_headaches<-function(x,y){
if (is.na(x)|is.na(y)){
output<-NA
}
else if (x==2){
if (y==2){
output<-'previous_headache_maintained'
}else if(y==0){
output<-'previous_headache_ceased'
}
}else if(x %in% c(0,774,775,776)){
if (y==2){
output<-'new_onset_headache'
}else if (y %in% c(0, 774, 775, 776)){
output<-'no_headache'
}
}
}
Q10_incidence<-mapply(incidence_headaches, Q10_headache_tibble[,1], Q10_headache_tibble[,2])
当我打电话时
mapply(incidence_headaches, Q10_headache_tibble[,1], Q10_headache_tibble[,2])
在几个警告中,我得到了可怕的“条件长度 > 1,并且只会使用第一个元素”。我怎么能处理这个? 虽然我发现了几个关于相同“条件有长度(...)”警告的问题,但我仍然觉得这个话题很混乱。欢迎使用“傻瓜式”演练。
似乎和向量化有关,可以通过用嵌套的 ifelse() 结构替换函数来解决,这可能会很乱。
我可能需要在很多场合使用类似的功能,但不确定什么是最好的解决方法。
【问题讨论】:
-
如果函数的任何输入
x或y是长度 > 1 的向量,则is.na(x)或is.na(y)中的任何一个都是相同长度的向量,因此会出现警告.解决方案是使用ifelse。你能从这里走吗?
标签: r if-statement mapply