【发布时间】:2022-11-23 01:45:04
【问题描述】:
我正在处理以下需要使用 case_when 的问题。但是,我遇到错误消息Error: must be a logical vector, not a double vector,因为替换的列不是同一类型(由于bind_rows,有些是逻辑的,有些是双重的)。我正在寻找一个干净的解决方案来获得所需的输出。
#set empty dataframe with column names
df <- setNames(data.frame(matrix(ncol = 5, nrow = 0)), c("a", "b", "c","d","e"))
df_subset <- data.frame(b=c(1,2))
df1 <- bind_rows(df,df_subset)%>%mutate(type="b")
df1
a b c d e type
1 NA 1 NA NA NA b
2 NA 2 NA NA NA b
df1%>%mutate(result=case_when(type=="a"~a,
type=="b"~b,
type=="c"~c,
type=="d"~d,
type=="e"~e,
T~NA_real_))
Error: must be a logical vector, not a double vector
预期输出:(注意:我并不总是知道 b 列是否有值)
df1%>%mutate(a=NA_real_,
c=NA_real_,
d=NA_real_,
e=NA_real_,
result=case_when(type=="a"~a,
type=="b"~b,
type=="c"~c,
type=="d"~d,
type=="e"~e,
T~NA_real_))
#desired output
a b c d e type result
1 NA 1 NA NA NA b 1
2 NA 2 NA NA NA b 2
【问题讨论】:
标签: r