R Loop error using character - r

I have the below function which inserts a row into a table (new_scores) based upon the attribute that I feed into it (where the attribute represents a table that I select things from):
buildNewScore <- function(x) {
something <- bind_rows(new_scores,x%>%select(ATT,ADJLOGSCORE))
return(something)
}
Which works fine when I define x.
But when I try to create a for loop that feeds the rest of my attributes into the function it falls over as I'm feeding in a character.
attlist <- c('Z','Y','X','W','V','U','T','RT','RO')
record_count <- length(attlist)
for (x in c(1:record_count)){
buildNewScore(attlist[x])
}
I've tried to convert the attribute into other classes but I can't get the loop to use anything I change it to (name, data.frame etc.).
Anyone have any ideas as to where I'm going wrong - is my attlist vector in the wrong format?
Thanks,
Spikelete.

Related

Is there a good way to make conditional column names that reference a list in R?

I have a list of items that would like to check my field titled 'events' for. my desired output is another field in the table for each item in my list, which contains a count of that item for each row. I have little experience writing for loops and am stuck, but below is the logic of what I'm looking for.
events <- c('screen_view','cta','os_update')
for (i in events) {
event_data_consumer$i <- str_count(event_data_consumer$event,'i')
}
Does anyone know of a way to do this? Possibly in apply/lapply etc ?
The for loop code had two issues - 1) $i - will literally create a column i instead of the value from for each loop. Here, we can use [[. 2) 'i' will again be taken string "i" instead of the value, so we don't need a quoted value
library(stringr)
for(i in events) {
event_data_consumer[[i]] <- str_count(event_data_consumer$event, i)
}
Or with lapply, loop over the vector of events with lapply, get the count of strings from the 'event' column and assign it to new columns in the data with [
event_data_consumer[events] <- lapply(events, function(x)
str_count(event_data_consumer$event, x))

Looping through list and concatenating strings in R (Syntax)

I'm trying to create a loop that goes from 1 to 14. Each integer in this loop would be added to the end of the name of a newly created dataframe. Then, it should search a column in an existing dataframe based on the concatenation of a number and text. I've been searching for hours but cannot find a solution.
What I mean is:
while (i <= 14) {
"newDF" + i <- oldDf %>%
filter(str_detect(ColumnName, "TEXT" + i)
}
The new dataframes should look like this:
newDF1,newDF2... newDF14
They should be created based on a concatenated string (text + i):
text1,text2..text14
My first challenge is to create a new dataframe based on the concatenation of text and i. I've tried using the str_c command and the str_glue command but get the following error message.
Error in str_c("newDF", i)) <- oldDF:
target of assignment expands to non-language object
Error in str_glue("newDF{i}") <- oldDF:
target of assignment expands to non-language object
The major problem with your code above is that you can't have any operations to the left of your assignment operator.
for (i in 1:14){
assign(str_glue("newDF{i}"), oldDF %>%
filter(str_detect(ColumnName, str_glue("TEXT{i}"))))
}
So technically, this would work even though I feel like there's a better way to do this either with nested lists or using spread and gather. I would say more, but I don't have enough context to solve the problem.

For loops and removing rownames

I'm trying to remove the row names for all of my data using a for loop to make it shorter, but It is creating a new value called "i" rather than removing the rownames
this is the example of my code where U91, etc are my data.
for (i in c(U91,P95,P98,E10)) {
rownames(i) <- NULL
}
I have also tried using quotations inside the c() and still an error this instead creates an i value of "E10"
Another Problem I'm having with is trying to loop this function:
Caltex <- Main[Fuel=="Caltex", ]
for (i in c("7-Eleven","Caltex","Indie")) {
i <- Main[Brand==i, ]
}
rownames(dataframe) returns 'string' of vector. So, if want to remove or to do any operation of 'rownames' try to create a vector of string.
for example:
c("U91","P95","P98","E10") and then 'rownames(i) <- NULL'
to answer your second question: Please remember you are handling string. String does not work the same way it works for numbers.
Please explain your second question elaborately about your variables and string input. So, that I could help on this.

Referencing a function parameter in R

I'm working on a function and need to know how to reference the incoming parameters.
For example, in python or lots of other languages, you can reference the input parameters something like this:
sys.argv[1:].
How can I reference the name of a parameter in R?
The specific problem I'm trying to solve is I want to capture the string value of the incoming parameter, so I can paste it as a concentration with a list of column_names I want to iterate through.
Here's the head of the function call, just so you can see the incoming parameter:
function(df_in)
So here's an example of the code I am writing and I want the string value of the dataframe_in, not the object that it references.
col_name <-paste(df_in,varnames[i],sep="$")
if df_in contained "my_df" and the current column_name is my_col, I'm trying to have col_name in the example above set to my_df$my_col.
I was thinking of using the get() function but quite sure how to apply it in this situation.
Thanks
Try something along these lines:
fn1 <- function(df_in){ in_nam <- deparse(substitute(df_in) )
col_names <-paste(in_nam, names(df_in), sep="$")
cat(col_names) }
> dfrm <- data.frame(a=1:10, b=letters[1:10])
> fn1(dfrm)
#dfrm$a dfrm$b
You didn't say what varnames was supposed to be so I'm guessing you want the column names from the object. BTW, don't expect to be able to reference the column values with those character values. They are no longer language objects.

In R, package xts, how would one iterate period subsetting over a list without throwing errors?

Assume:
list of n xts objects in .GlobalEnv with the suffix ".raw" (e.g: ABC.raw)
have created a list of .raw names in a list (ie, rawfiles <- ls(pattern="*.raw",envir=.GlobalEnv))
Would like to:
loop or lapply through rawfiles and subset a particular timeperiod in each iteration
for example, to write this as a single line would be: new <- ABC.raw["T09:00/T10:00"] if I wanted to subset ABC.raw from 9am to 10am each day.
The problem is:
Doesn't seem to be an easy way of passing["Thh:mm/Thh:mm"] to a loop, apply or assign without causing errors.
Any ideas how to pass this?
In pidgeon code, I guess I'm looking for a working equivalent of:
for(i in 1:length(raw)){
raw[i]["T09:00/T10:00"]
}
Many thanks in advance for any assistance on this.
Try get.
get(x) retrieves the variable whose name is stored in x, so foo<-1; get('foo') would return 1.
for ( rawname in rawfiles ) {
get(rawname)["T09:00/T10:00"]
}

Resources