database - How to use an if...else statement in R? -
i'm trying create variable using if-statement. want check whether variable "st" exists in dataframes in list of dataframes "dflist", , if doesn't exist want create variable "st". tried this(however, doens't work):
#making list of dataframes, , reading them r mylist = list.files(pattern="*.dta") dflist <- lapply(mylist, read.dta13) # if "st" exists in every dataframe in dflist, return "yes", else if doesn't exist in particular dataframe, create variable "st" in dataframes if(exists(st, dflist)){ "yes" } else{ st <- c("total") dflist$st <- st }
we can use lapply
loop on list
, create column in 'data.frame' if
'st' not there.
dflist1 <- lapply(dflist, function(x) if(!exists("st", x)) transform(x, st = "total") else x)
data
dflist <- list(data.frame(v1 = 1:5), data.frame(st = 1:6))
Comments
Post a Comment