ab<- as.factor(c("A","B","A","C","B","C","C"))
a123<- as.factor(c(NA,NA,NA,465,NA,532,456))
dd<- as.data.frame(cbind(ab,a123))
这是我拥有的数据框,如果列ab的值为A,我想用0替换NA值,否则NA = 1。
我尝试过以下代码:
dd$Amount[is.Na(dd$Amount)]<- ifelse(my_dd$Activity=="Beneficiary Added", 0,1)
我收到以下错误:
> dd$Amount[is.Na(dd$Amount)]<- ifelse(my_dd$Activity=="Beneficiary Added", 0, 1)
Error in `*tmp*`$Amount : object of type 'closure' is not subsettable
答案 0 :(得分:0)
这是我的建议。
abc<- c("A","B","A","C","B","C","C")
df<- data.frame(cbind(abc,a123),stringsAsFactors =FALSE)
df$your_var=ifelse(df$abc %in% "A" & df$a123 %in% NA, 0, ifelse(df$a123 %in% NA,1,df$a123)
print(df)
最佳
帕夫洛
答案 1 :(得分:0)
我的评论作为答案加上data.table
的例子(我认为语法更加清晰):
library(data.table)
df <- data.frame(abc = c("A","B","A","C","B","C","C"), a123 = c(NA,NA,NA,465,NA,532,456))
dt <- data.table(df)
# "Classic" data.frame syntax
df$a123[is.na(df$a123)] <- ifelse(df[is.na(df$a123), 'abc'] == "A", 0, 1)
# data.table one
dt[is.na(a123), a123 := ifelse(abc == "A", 0, 1)]