我正在尝试使用if语句创建变量。我想检查变量“st”是否存在于数据帧“dflist”列表中的数据帧中,如果它不存在,我想创建变量“st”。我尝试这样做(但是,它不起作用):
#making list of dataframes, and reading them into r
mylist = list.files(pattern="*.dta")
dflist <- lapply(mylist, read.dta13)
# if "st" exists in every dataframe in dflist, return "yes", else if it doesn't exist in a particular dataframe, create variable "st" in those dataframes
if(exists(st, dflist)){
"yes"
} else{
st <- c("total")
dflist$st <- st
}
答案 0 :(得分:1)
我们可以使用lapply
循环list
并在'data.frame'中创建一个列if
'st'不存在。
dflist1 <- lapply(dflist, function(x) if(!exists("st", x))
transform(x, st = "total") else x)
dflist <- list(data.frame(v1 = 1:5), data.frame(st = 1:6))