我试图创建一个新变量(NPHOURS),其值将是以第三个变量(PROD)的值等于"为条件的第二个变量(HOURS)的值。 N",否则我希望(NPHOURS)的值为" 0"。
示例数据:
samp<-structure(list(HOURS = c(4.05, 4.05, 3.95, 3.95, 1), PROD = structure(c(2L,
1L, 2L, 1L, 1L), .Label = c("N ", "Y "), class = "factor"), NPHOURS = c("0",
"0", "0", "0", "0")), .Names = c("HOURS", "PROD", "NPHOURS"), row.names = c(NA,
5L), class = "data.frame")
以下ifelse语句仅生成&#34; 0&#34;。
samp$NPHOURS <- ifelse(samp$PROD == "N", samp$HOURS, 0)
有人可以帮忙吗?
答案 0 :(得分:0)
str(samp$PROD)
所以......在&#34; N&#34;之后报告空白....
samp$NPHOURS <- ifelse(samp$PROD == "N ", samp$HOURS, 0)
答案 1 :(得分:0)
我们也可以
i1 <- grep('N', samp$PROD)
samp$NPHOURS[i1] <- samp$HOURS[i1]