Combining a for loop with meta characters - r

Im writing a for loop that checks whether values in a particular column match a predefined list.
So it's kind of like this:
money <- read.csv2("money.csv", header = T)
#set counter
count_financial = 1
#set list
financial_items <- c("bank", "ABN Amro")
for (i in 1:nrow(money)) {
if(money$Description[i] in financial_items ) {
count_financial = count_financial + 1
}
}
It's working for now but I actually want to tweak it a little and use metacharacters. So I cant only find items which say "Bank" or "ABN Amro" but also lines which "bank cost" or "ABN Amro transaction".
Any thoughts on how I can do this?

Try:
length(financial_items %in% money$Description)
But if you are intent on using the loop:
for (i in 1:nrow(money)) {
if(money$Description[i] %in% financial_items ) {
count_financial = count_financial + 1
}
}
Update:
Upon rereading the question, I think you are looking for:
length(grep("bank|abn amro", money$Description, ignore.case=TRUE))

You could try
filtered <- money[grep("bank|ABN Amro",money$Description,ignore.case=TRUE),]
count_financial <- nrow(filtered)

Related

Loop command only consist of last value

I am trying to read.csv a series of file named ("year".csv) from year 2005 to 2007 and writing into database.
However the loop command only consist of "2007L" for element "i" and only read 2007.csv into the dataframe.
Any ideas on how to resolve the issue ?
for(i in c(2005:2007)){
ontime<-read.csv(paste0(i,".csv"), header=TRUE)}
if(i == 2005){
dbWriteTable(conn,"ontimet",ontimet)
} else {
dbWriteTable(conn,"ontimet",ontimet, append= TRUE)
}
}
Something like this might be what you need. I think you just need to assign variables and append in the right place.
You probably need is like this. It produces all three years (or in your case, it would be csv's)
tmp = NULL
for(i in c(2005:2007)){
if(i == 2005){
tmp = append(tmp, i)
} else {
tmp = append(tmp, i)
print(tmp)
}
}

why c() does not working in this recursive function in R?

enter image description here
I know there exists function 'unique' which works similar to what I want to make, but I want to make this function.
I want this function finally returns 'result' which contains unique elements of input vector.
But I don't know why this function's result is totally different from my expect.
Why c which is to combine before result and new unique element is not working.
Please tell me how to fix my code.
Thank you.
I think what you expect might be something like below, where result should be an argument of m_uni:
m_uni <- function(x,result = c()) {
if (class(x)=='numeric'| class(x)=='character') {
if (length(x) <= 1){
return(result)
} else {
if (x[length(x)] %in% result) {
x <- x[-length(x)]
m_uni(x,result)
} else {
result <- c(result,x[length(x)])
x <- x[-length(x)]
m_uni(x,result)
}
}
} else {
return('This function only gets numeric or character vector')
}
}
such that
> m_uni(x)
[1] 0 4 5 -2

In R, how to read multiple integers from user prompt?

I need to create a vector with multiple inputs (integers) from user.
The intent is to create a list and verify if it has a mode and where is its median.
I am using this code:
ReadVector <- function()
{
x <- 0
while(x<16) {
n <- readline(prompt="Input one integer: ")
return(as.integer(n))
VectorUser <- c(n)
x <- x+1
}
print(VectorUser)
}
ReadVector()
And I can only get one integer, I dont know if my mistake is in the while loop or(and) in the concatenate command after it. Can you help me?
Does this work for you?
ReadVector <- function()
{
x <- 0
myvector = vector()
while(x<16) {
n <- readline(prompt="Input one integer: ")
myvector = c(myvector,n)
x <- x+1
}
return (as.integer(myvector))
}
You need yo save your values in a vector, and keep it (without returning inside the loop), until you completed it.
Hope it helps
ff=function(){
d=c()
while (TRUE){
int = readline('ENTER to quit > ')
if(nchar(int)==0) {
if(length(d)>0)cat("The numbers you entered are:",d)
else(cat("You did not enter any number!!"));break}
else{
value=suppressWarnings(as.integer(int))
if(!is.na(value)){cat(value);d=c(d,value)} else cat(ran[sample(6,1)])
}}
ff()

if/else statement evaluating only else statement

Disclaimer: This is a question regarding an assignment for a Coursera course.
I'm having trouble coming up with a way to create a new column that differentiates between weekdays and weekends in my data set. I'm using a nested if/else statement within a for loop. The problem is the output makes every row 'weekday'. Does anyone see something glaringly wrong with my code? My end goal is to create a new factor variable that is either "weekend" or "weekday."
df4 <- mutate(df4, day = weekdays(df4$date))
for (i in df4$day) {
if(i %in% c("Saturday",'Sunday')) {
df4$day_type <- 'weekend'
} else {
df4$day_type <- 'weekday'
}
}
I modify a little bit of your code .(see below)
for (i in 1 : dim(df4)[1]) {
if(df4$day[i] %in% c('Saturday','Sunday')) {
df4$day_type[i] <- 'weekend'
} else {
df4$day_type[i] <- 'weekday'
}
}

using 'input$entry' inside paste0 for variable length entry[1:n]

I have a clunky block of shiny code on server.R side that I feel R syntax ought to allow me make one or two lines and simultaneously more flexible with some kind of lapply or do.call line
if(input$parVary == "area" && as.numeric(input$nTraces) > 3 )
{
area <- c(input$area, input$area2, input$area3, input$area4)
} else if(input$parVary == "area" && as.numeric(input$nTraces) > 2 )
{
area <- c(input$area, input$area2, input$area3)
} else if(input$parVary == "area" && as.numeric(input$nTraces) > 1 )
{
area <- c(input$area, input$area2)
} else
{
area <- input$area
}
But I have spent a day and about a billion different combos of lapply, do.calls, reactive, get, c, and observes around
paste0('input$area', 1:as.numeric(input$nTraces))
I just can't seem to find the right combination or figure out the reactive concept I'm missing. It -seems- to be related to the code not ever including individual input$area1, input$area2, etc... explicit text anywhere in the code?
I spoke a little too soon in comment above. My specific code ended up needing conditional to handle the list versus single value case. But #NicE answer is one I was looking for. Five sections like
if(input$parVary == "area" && as.numeric(input$nTraces) > 1 )
{
area <- lapply(paste0("area",1:as.numeric(input$nTraces)),function(x) input[[x]])
} else
{
area <- input$area1
}
teamed with later
mySolution <- list()
if(input$nTraces =='1')
{
mySolution <- solveCalc(dat=dat,tox=tox,area=area,temp=temp,model=modelIn)
} else
{
mySolution <- switch(input$parVary,
"model" = lapply(modelIn,solveCalc,dat=dat,tox=tox,area=area,temp=temp),
"temp" = lapply(temp,solveCalc,dat=dat,tox=tox,area=area,model=modelIn),
"tox" = lapply(tox,solveCalc,dat=dat,temp=temp,area=area,model=modelIn),
"Vt" = lapply(dat,solveCalc,tox=tox,temp=temp,area=area,model=modelIn),
"area" = lapply(area,solveCalc,dat=dat,tox=tox,temp=temp,model=modelIn)
)
}
Got me just what I wanted.

Resources