I've a data frame with several variables in R. I want to use a while loop to go through all of the records and assign a new value to the record. I tried while loop which look like this:
h$est=""
i=0
while (i<188){
if (h$nr==2) {h$est=="X"}
else {h$est==21}
i=i+1
}
and it is not working at all.
I know how to make it via
h$est[h$nr==2]<-"X"
But I'd like to make it with while loop.
Ok I figure it out, The code should be like that:
for (i in 1:length(h$Treatment)){
if (h$Treatment[i]=="ASP") {h$est[i]=3}
else {h$est[i]=1}
}
Related
I want to see the level as an output of several variables.
Let's say I have 9 variables, and I could do it like this:
levels(myd$tel_1)
levels(myd$tel_2)
levels(myd$tel_3)
...
But I want to improve it by using a for loop. I think it's useless to use the same function instead of the same code copied underneath.
I've tried something like this:
block <-
c("tel_1",
"tel_2",
"tel_3",
"tel_4",
"tel_5",
"tel_6",
"tel_7",
"tel_8",
"tel_9")
for (j in block) {
levels(myd[[j]])
}
But this does not work, no error message, nothing. Only the code copied into the console.
Thanks for help!
I have problems with my coded loop for some of my variables. I have run it firstly with one variable and it ran fine. Upon entering a different variable and different data range, the loop did not include all the outputs that it should have done according to the loop. There was no error message. The code for the loop is below:
geartype=data[179:187]
data_stats_structure_gt=as.data.frame(matrix(nrow=0,ncol=3))
names(data_stats_structure_gt)=c('Gear.Type','Man_Kendall_pvalue','Man_Kendall_tauv')
for (i in 1:ncol(geartype)){
dat=geartype[,i]
dat=as.data.frame(cbind(data$ï..Year,dat))
ds=names(geartype)[i]
names(dat)=c("Year",names(geartype)[i])
dat=dat[-which(is.na(dat[,2])==TRUE),]
if(nrow(dat)>=3){
output=as.data.frame(matrix(nrow=1,ncol=3))
names(output)=c('Gear.Type','Man_Kendall_pvalue','Man_Kendall_tauv')
output$Gear.Type=names(geartype)[i]
output$Man_Kendall_pvalue=mk.test(dat[,2])$p.value
output$Man_Kendall_tauv=mk.test(dat[,2])$estimates[3]
data_stats_structure_gt=rbind(data_stats_structure_gt,output)
}
}
I am creating a fairly simple GUI in R that creates figures of different data analysis based on values selected by a user. I am having trouble figuring out how to enable a user to select multiple values from a list. The method I am working on is below. The problem area is in the if statement which is where I need to place the user selections into a list.
CallSpecies<-function(options){
dialog<-gtkMessageDialog(NULL,0,"question","ok-cancel","Choose a species",show=FALSE)
sppmodel<-rGtkDataFrame(Species)
sppview<-gtkTreeView(sppmodel)
sppview$getSelection()$setMode("multiple")
column<-gtkTreeViewColumn("Species Code",gtkCellRendererText(),text=0)
column1<-gtkTreeViewColumn("Common Name",gtkCellRendererText(),text=1)
sppview$appendColumn(column)
sppview$appendColumn(column1)
scrolled_window<-gtkScrolledWindow()
scrolled_window$setSizeRequest(-1,150)
scrolled_window$add(sppview)
dialog[["vbox"]]$add(scrolled_window)
if (dialog$run()==GtkResponseType["ok"]){
}
dialog$destroy()
}
I ended up solving my own issue after quite a bit of reading documentation from other languages and translating it to R syntax. I have edited the code to show my solution. I am by no means an expert in R or GTK but this seems to work.
CallSpecies<-function(options){
dialog<-gtkMessageDialog(NULL,0,"question","ok-cancel","Choose a species. Hold control and click to select multiple species.",show=FALSE)
sppmodel<-rGtkDataFrame(Species)
sppview<-gtkTreeView(sppmodel)
sppview$getSelection()$setMode("multiple")
column<-gtkTreeViewColumn("Species Code",gtkCellRendererText(),text=0)
column1<-gtkTreeViewColumn("Common Name",gtkCellRendererText(),text=1)
sppview$appendColumn(column)
sppview$appendColumn(column1)
scrolled_window<-gtkScrolledWindow()
scrolled_window$setSizeRequest(-1,150)
scrolled_window$add(sppview)
dialog[["vbox"]]$add(scrolled_window)
spplist<-c()
if (dialog$run()==GtkResponseType["ok"]){
selection<-sppview$getSelection()
sel_paths<-selection$getSelectedRows()$retval
i=1
for (p in sel_paths){
sel_row<-sel_paths[[i]]$getIndices()[[1]]
sel_row<-sel_row+1
elem<-Species[sel_row,"SpeciesCode"]
elem<-as.character(elem)
spplist<-c(spplist,elem)
i<-i+1
}
print("spplist")
print(spplist)
}
dialog$destroy()
}
I am trying to scrape data from a website which is unfortunately located on a very unreliable sever which has very volatile reaction times. The first idea is of course to loop over the list of (thousands of) URLs and saving the downloaded results by populating a list.
The problem however is that the server randomly responds very slowly which results into a timeout error. This alone would not be a problem as I can use the tryCatch() function and jump to the next iteration. Doing so I am however missing some files in each run. I know that each of the URLs in the list exists and I need all of the data.
My idea thus would have been to use tryCatch() to evaluate if the getURL() request yields and error. If so the loop jumps to the next iteration and the erroneous URL is appended at the end of the URL list over which the loop runs. My intuitive solution would look something like this:
dwl = list()
for (i in seq_along(urs)) {
temp = tryCatch(getURL(url=urs[[i]]),error=function(e){e})
if(inherits(temp,"OPERATION_TIMEDOUT")){ #check for timeout error
urs[[length(urs)+1]] = urs[[i]] #if there is one the erroneous url is appended at the end of the sequence
next} else {
dwl[[i]] = temp #if there is no error the data is saved in the list
}
}
If it "would" work I would eventually be able to download all the URLs in the list. It however doesn't work, because as the help page for the next function states: "seq in a for loop is evaluated at the start of the loop; changing it subsequently does not affect the loop". Is there a workaround for this or a trick with which I could achieve my envisaged goal? I am grateful for every comment!
I would do something like this(explanation within comments):
## RES is a global list that contain the final result
## Always try to pre-allocate your results
RES <- vector("list",length(urs))
## Safe getURL returns NA if error, the NA is useful to filter results
get_url <- function(x) tryCatch(getURL(x),error=function(e)NA)
## the parser!
parse_doc <- function(x){## some code to parse the doc})
## loop while we still have some not scraped urls
while(length(urs)>0){
## get the doc for all urls
l_doc <- lapply(urs,get_url)
## parse each document and put the result in RES
RES[!is.na(l_doc )] <<- lapply(l_doc [!is.na(l_doc)],parse_doc)
## update urs
urs <<- urs[is.na(l_doc)]
}
I need help on the following code
I tried to generate a random series using while clause and met the following problem
When run codes as below
m1=0.82
set=rep(1, 1000)
while(mean(set)!=m1){
k=sample(1:1000,1)
if(set[k]!=0){set[k]=0}
}
every thing is fine, however the loop can end if I change ml as as below
m1=1-0.18
set=rep(1, 1000)
while(mean(set)!=m1){
k=sample(1:1000,1)
if(set[k]!=0){set[k]=0}
}
just change from ml=0.82 to ml=1-0.18, R can't stop looping.