removing elements of the environment using a loop - r

I have 16 elements in the environment called Factor1 to Factor16. I would like to remove them automatically. I wrote that and I cannot understand why that's not working...
for(i in 1:16) {
rm(paste0('Factor',i))
}
sorry for this basic question, I am a beginner!

for(i in 1:16) {
rm(list=paste0('Factor',i))
}
although rm(list=paste0('Factor',1:16)) or rm(list=ls(pattern="Factor"))would be more appropriate...

Related

How to handle variable not defined error in r

Is there a way to evade variable not defined error in r? For example the code below throws variable not defined error.
for(i in length(someList)){
print(someList[[i]])
}
Can I check if a variable exists first before executing the code above. A pseudocode would look like this:
if(someList exists){
for(i in length(someList)){
print(someList[[i]])
}
} else cat("The variable does not exist")
Are you looking for the exists function?
someList <- list(1,2,3)
if (exists("someListNot")){
for(i in length(someListNot)){
print(someListNot[[i]])
}
}
if (exists("someList")){
for(i in 1:length(someList)){
print(someList[[i]])
}
}
You can use the exists("myVariable") function to check existence.
Also make sure your loop is really looping! If you use for (i in length(variable) it will only use the last index of your variable instead of looping over it.
You code could look something like this:
if ( exits("myVariable")){
for(i in seq_len(length(someList))){
print(someList[[i]])
}
}

loop problems make frequency table in R

library(MASS)
with (survey,
for (variable in names(Filter(is.factor, survey))) {
print(table(variable))
}
)
I'd like to make frequency tables for all factor variables.
But, it doesn't work.
need some help.
Here is another solution:
lapply(Filter(is.factor, survey), table)
Here is a slight modification that works.
for (variable in names(Filter(is.factor, survey))) {
print(table(survey[[variable]]))
}
To use with() with a character as you have tried you could do (not necessarily recommended):
with(survey,
for (variable in names(Filter(is.factor, survey))) {
print(table(eval(as.symbol(variable))))
}
)

R code does not work when called from function

HI i just started learning R and finding this problem to be really interesting where I just run a code directly without wrapping in a function it works but when I place it inside a function it doesn't work, What can be possible reason?
fill_column<-function(colName){
count <- 0
for(i in fg_data$particulars) {
count <- count +1
if(grepl(colName, i) && fg_data$value[count] > 0.0){
fg_data[,colName][count] <- as.numeric(fg_data$value[count])
} else {
fg_data[,colName][count] <- 'NA'
}
}
}
fill_column('volume')
Where I am creating new column named volume it this string exists in particulars column.
I have added a comment where solution given by another question does not work for me, Please look at my comment below.
Finally I got it working but reading another answer on SO, here is the solution:
fill_column <- function(colName){
count <- 0
for(i in fg_data$particulars) {
count <- count +1
if(grepl(colName, i) && fg_data$value[count] > 0.0){
fg_data[,colName][count] <- as.numeric(fg_data$value[count])
} else {
fg_data[,colName][count] <- 'NA'
}
}
return(fg_data)
}
fg_data = fill_column('volume')
Now reason, Usually in any language when we modify global object inside any function it reflects on global object immediately but in R we have to return the modified object from function and then assign it again to global object to see our changes. or another way for doing this is to assign local object from within the function to global context using envir=.GlobalEnv.

Writing the results of the for loop

We were trying to write the results from a for loop. We tried to use write.table, as.data.frame and other solutions, but with no success. We expect to have a data frame.
Currently we have only the loop, that shows year and values from a matrix which are bigger than 50. Looks like that:
for (i in 1:nrow(dobowe1)) {
if(dobowe1[i,4]>50) {
cat(dobowe1[i,"rok"],dobowe1[i,4], "\n")
}
}
Note: We don't do programming a lot, so it's hard to use other solutions from the questions that already beed asked.
Try to save each element to the vector, like here:
tabela <- numeric(nrow(dobowe1))
for (i in 1:nrow(dobowe1)) {
if(dobowe1[i,4]>50) {
tabela[i] <- paste(dobowe1[i,"rok"],dobowe1[i,4])
}
}
as.data.frame(tabela)
If you just want to visually inspect a subset of your matrix, you can just print out a filtered subset:
# create the filter:
> f <- dobowe1[,4] > 50
# use the filter to subset (index) your data.frame:
> dobowe1[f,c("rok", whatever-4th-var-is-called)]
This will automatically print it out. Or you can write it to a file with ?write.table

how to subtract two vectors in OpenBUGS

I am having a very hard time trying to subtract two vectors in my OpenBUGS model. The last line of the code below keeps giving the error "expected right parenthesis error":
model {
for ( i in 1:N) {
for(j in 1:q) {
vv[i,j] ~ dnorm(vz[i,j],tau.eta[j])
}
vz[i,1:q] ~ dmnorm(media.z[i,], K.delta[,])
for(j in 1:q) {
mean.z[i,j] <- inprod(K[i,] , vbeta[j,])
}
K[i,1] <- 1.0
for(j in 1:N) {
K[i,j+1] <- sum(ve[,i] - ve[,j])
}
}
If I change that line to K[i,j+1] <- sum(ve[,i]) - sum(ve[,j]), then the model works fine, but that is not what I want to do. I would like to subtract element-wise.
I searched SO for OpenBUGS, but there are only a few unrelated topics:
OpenBUGS - Variable is not defined
OpenBUGS: missing value in Bernoulli distribution
In Stats Stack Exchange there is this post which is close, but I still could not make how to implement this in my model:
https://stats.stackexchange.com/questions/20653/vector-multiplication-in-bugs-and-jags/20739#20739
I understand I have to write a for loop, but this thing is sure giving me a big headache. :)
I tried changing that line to:
for(k in 1:p) { temp [k] <- ve[k,i] - ve[k,j] }
K[i,j+1] <- sum(temp[])
where 'p' is the number of rows in each 've'. Now I keep getting the error "multiple definitions of node temp[1]".
I could definitely use some help. It will be much appreciated.
Best regards to all and thanks in advance!
PS: I wanted to add the tag "OpenBUGS" to this question but unfortunately I couldn't because it would be a new tag and I do not have enough reputation. I added "winbugs" instead.
The "multiple definitions" error is because temp[k] is redefined over and over again within a loop over i and another loop over j - you can only define it once. To get around that, use i and j subscripts like
for(k in 1:p) { temp[k,i,j] <- ve[k,i] - ve[k,j] }
K[i,j+1] <- sum(temp[,i,j])
Though if that compiles and runs, I'd check the results to make sure that's exactly what you want mathematically.

Resources