Loop using columns on objects in R

Asked

Viewed 181 times

2

Hello, I created more than 8 thousand objects (Dataframes) in R. However, when trying to loop one of the columns of each object, I always have answers that the function used does not read non-numerical objects. how do I fix this?

for(i in 10:13) { 
    nam <- paste("mu04mun_", i, sep = "")
    d <- paste0("sub04mun", i, "$des_flo_04")
    assign(nam, qnorm(d))
}

Error in qnorm(d) Non-numerical argument for mathematical function

1 answer

1

You are applying the function qnorm() in a text array. See:

d <- "texto"
qnorm(d)
#> Error in qnorm(d): Non-numeric argument to mathematical function

Apparently his intention was to rotate qnorm() in the column des_flo_04 of data frame sub04mun. For this, you need to call the object, not the text.

Rui’s suggestion will not work directly, because you can not put the $ within the get, but you can do it this way:

for(i in 10:13) { 
    nam <- paste("mu04mun_", i, sep = "")
    d <- paste0("sub04mun", i)
    assign(nam, qnorm(d)[["des_flo_04"]])
}

It is important to note that this type of code is not recommended. The ideal here is for you to work with lists (save data frames in a list) and operate on top of lists: for example, see this answer here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.