假设我有这个data.frame:
tdata <- structure(list(fyear = c("1971", "1971", "1971", "1971", "1971",
"1971", "1971", "1971", "1971", "1971", "1971", "1971", "1972",
"1972", "1972", "1972", "1972", "1972", "1972", "1972", "1972",
"1972", "1972", "1972", "1972", "1973", "1973", "1973", "1973",
"1973", "1973", "1973", "1973", "1973", "1973", "1973", "1973",
"1974", "1974", "1974", "1974", "1974", "1974", "1974", "1974",
"1974", "1974", "1974", "1974", "1975", "1975", "1975", "1975",
"1975", "1975", "1975", "1975", "1975", "1975", "1975")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -60L), .Names = "fyear")
如果tdata$check
,我想将1分配给fyear == 1975
。我试过这个if语句,但是它引发了一个错误
if(tdata$fyear == 1975)) tdata$check <- 1
错误:
Warning message:
In if (ex$fyear == 1975) ex$check <- 1 :
the condition has length > 1 and only the first element will be used
答案 0 :(得分:2)
试试这个
tdata$check <- (tdata$fyear==1975)*1
答案 1 :(得分:1)
上面的布尔方法很聪明,但要分配任何值:
tdata$check[tdata$fyear==1975] <- 1
如果你想要0而不是NAs
tdata$check <- 0
tdata$check[tdata$fyear==1975] <- 1
答案 2 :(得分:1)
或者
tdata$check[tdata$fyear==1975]<-1
产生一列1(如果为真)或NA,如果不是真的话。