R for Loop Add Value to New Column - r

I am trying to run a for loop in a R data frame to pull the Last Price of dataframe of stocks. I am having trouble appending the result to the original dataframe and using it as a second column. Here is the code I am working with thus far. I can get it to print but not add to a new column. I tried to set the loop value equal to a new column but I get an error
for (i in df_financials$Ticker){
df_financials$Last_Price=(bdp(i,'PX_LAST'))
}
Error in `$<-.data.frame`(`*tmp*`, "Last_Price", value = list(PX_LAST =
NA_real_)) :
replacement has 1 row, data has 147
Print(df_financials)
Ticker
1 ENH Equity
2 AXS Equity
3 BOH Equity
4 CNA Equity
5 TRH Equity

You first need to specify the order to apply your command to the stated vector and when to stop [i.e., use 1:length(df$Var) within for()]. Second, specify which row (i) of your new column to replace (i.e.,df$var[i]). Give the code below a try and see if that works.
for (i in 1:length(df_financials$Ticker)){
df_financials$Last_Price[i]=(bdp(i,'PX_LAST'))
}
I'm not familiar with the bdp() function itself. However, I suspect the
problem is that you are trying to pull data from a list with more stocks than you are interested in. If this is the case you need to reference the stock in row i that you want to obtain the last price for. If I'm understanding this correctly the code below should do the trick.
I'll assume that the list is something like
Stock<-data.frame(other_stocks = c("ENH","AXS","Rando1","BOH","CNA","TRH","Rando2","Rando3"),
PX_LAST=c(1,2,3,4,5,6,7,8))
Stock
for (i in 1:length(df$Ticker)){
df$Last_Price[i]=(bdp(df$Ticker[i],'PX_LAST'))
}

Related

I am making a for/if loop and I am missing a step somewhere and I cant figure it out

strong text Below is my objective and the code I made to represent that Row 19 is the original street text and 24 is where street2 is located
https://www.opendataphilly.org/dataset/shooting-victims/resource/a6240077-cbc7-46fb-b554-39417be606ee << where the .csv is
Let's deal with the streets with '&' separating their names. Create a new column named street2 and set it equal to NA.
Then, iterate over the data frame using a for loop, testing if the street variable you created earlier contains an NA value.
In cases where this occurs, separate the names in block according to the & delimiter into the fields street and street2 accordingly.
Output the first 5 lines of the data frame to the screen.
Hint: for; if; :; nrow(); is.na(); strsplit(); unlist().
NewLocation$street2 <- 'NA'
Task7 <- unlist(NewLocation)
for (col in seq (1:dim(NewLocation)[19])) {
if (Task7[street2]=='NA'){
for row in seq (1:dim(NewLocation[24])){
NewLocation[row,col] <-strsplit(street,"&",(NewLocation[row,col]))
}
}
}

Working on loop and wanting some feedback, re-adding this to update code and list .csv

Acses to
https://www.opendataphilly.org/dataset/shooting-victims/resource/a6240077-cbc7-46fb-b554 39417be606ee
I have gotten close and got my loop to run, but not gotten the output I want
want a split of street # any '&' locations to a col called 'street$2
**Main objective explained et's deal with the streets with & separating their names. Create a new column named street2 and set it equal to NA.
Then, iterate over the data frame using a for loop, testing if the street variable you created earlier contains an NA value.
In cases where this occurs, separate the names in block according to the & delimiter into the fields street and street2 accordingly.
Output the first 5 lines of the data frame to the screen.
Hint: mutate(); for; if; :; nrow(); is.na(); strsplit(); unlist().
library('readr')
NewLocation$street2 <- 'NA'
#head(NewLocation)
Task7 <- unlist(NewLocation$street2)
for (row in seq(from=1,to=nrow(NewLocation))){
if (is.na(Task7[NewLocation$street])){
NewLocation$street2 <-strsplit(NewLocation$street,"&",(NewLocation[row]))
}
}
This is changing all on my street2 to equal street 1 and get rid of my "NA"s

Google Scripts automatically add date to column in Google Sheets

I am trying to use a Google script that retrieves 2 securities fields from GOOGLEFINANCE and saves the output to a Google Sheet file. I need the script to also add the datetime to the first column of the Sheet.
I have created a basic Google Sheet with 3 columns:
A is formatted to DateTime. It has column name date in row 1 and is empty in rows 2 onwards
C has the column name price in row 1 and is empty in rows 2 onwards
D has the column name pe in row 1 and is empty in rows 2 onwards
Here is my function:
function myStocks() {
var sh = SpreadsheetApp.getActiveSpreadsheet();
sh.insertRowAfter(1);
sh.getRange("A2").setValue(new Date());
sh.getRange("C2").setFormula('=GOOGLEFINANCE("GOOG", "price")');
sh.getRange("D2").setFormula('=GOOGLEFINANCE("GOOG", "pe")');
}
Here is the output:
Date price pe
12/10/2017 22:44:31 1037.05 34.55
12/10/2017 22:43:24 1037.05 34.55
The output of columns C and D is correct. The output of column A is wrong. Every time I run the function, each new row is added ABOVE the last row:
The first time I ran the function was at 12/10/2017 22:43:24 and it added that row first.
The second time I ran the function was 12/10/2017 22:44:31 BUT it added that row ABOVE the last row in the sheet - I wanted it to add the new row BELOW the last row.
Is there a way to auto fill the datetime downwards in a single column in GoogleSheets, using a script function?
How about the following modifications?
Modification points :
sh.insertRowAfter(1) means that a row is inserted between 1 row and 2 row.
In your situation, you can retrieve the last row using getLastRow().
getRange("A2").setValue(), getRange("C2").setFormula() and getRange("D2").setFormula() mean that the values are imported to "A2", "C2" and "D2", respectively.
By this, the values are always imported to 2 row.
When you want to import several values and formulas to sheet, you can use setValues() and setFormulas().
The script which was reflected above points is as follows.
Modified script :
function myStocks() {
var sh = SpreadsheetApp.getActiveSheet();
var lastrow = sh.getLastRow() + 1; // This means a next row of last row.
sh.getRange(lastrow, 1).setValue(new Date());
var formulas = [['=GOOGLEFINANCE("GOOG", "price")', '=GOOGLEFINANCE("GOOG", "pe")']];
sh.getRange(lastrow, 3, 1, 2).setFormulas(formulas);
}
Note :
In your script, date and 2 formulas are imported, simultaneously. The modified script works the same to this.
References :
insertRowAfter()
getLastRow()
setValues()
setFormulas()
If I misunderstand your question, please tell me. I would like to modify.

How to deal with non-consecutive (non-daily) dates in R, while looping?

I am trying to write a script that loops through month-end dates and compares associated fields, but I am unable to find a way to way to do this.
I have my data in a flatfile and subset based on 'TheDate'
For instance I have:
date.range <- subset(raw.data, observation_date == theDate)
Say TheDate = 2007-01-31
I want to find the next month included in my data flatfile which is 2007-02-28. How can I reference this in my loop?
I currently have:
date.range.t1 <- subset(raw.data, observation_date == theDate+1)
This doesnt work obviously as my data is not daily.
EDIT:
To make it more clear, my data is like below
ticker observation_date Price
ADB 31/01/2007 1
ALS 31/01/2007 2
ALZ 31/01/2007 3
ADB 28/02/2007 2
ALS 28/02/2007 5
ALZ 28/02/2007 1
I am using a loop so I want to skip from 31/01/2007 to 29/02/2007 by recognising it is the next date, and use that value to subset my data
First get unique values of date like so:
unique_dates<-unique(raw.data$observation_date)
The sort these unique dates:
unique_dates_ordered<-unique_dates[order(as.Date(unique_dates, format="%Y-%m-%d"))]
Now you can subset based on the index of unique_dates_ordered i.e.
subset(raw.data, raw.data$observation_date == unique_dates_ordered[i])
Where i = 1 for the first value, i = 2 for the second value etc.

To sort a specific column in a DataFrame in SparkR

In SparkR I have a DataFrame data. It contains time, game and id.
head(data)
then gives ID = 1 4 1 1 215 985 ..., game = 1 5 1 10 and time 2012-2-1, 2013-9-9, ...
Now game contains a gametype which is numbers from 1 to 10.
For a given gametype I want to find the minimum time, meaning the first time this game has been played. For gametype 1 I do this
data1 <- filter(data, data$game == 1)
This new data contains all data for gametype 1. To find the minimum time I do this
g <- groupBy(data1, game$time)
first(arrange(g, desc(g$time)))
but this can't run in sparkR. It says "object of type S4 is not subsettable".
Game 1 has been played 2012-01-02, 2013-05-04, 2011-01-04,... I would like to find the minimum-time.
If all you want is a minimum time sorting a whole data set doesn't make sense. You can simply use min:
agg(df, min(df$time))
or for each type of game:
groupBy(df, df$game) %>% agg(min(df$time))
By typing
arrange(game, game$time)
I get all of the time sorted. By taking first function I get the first entry. If I want the last entry I simply type this
first(arrange(game, desc(game$time)))
Just to clarify because this is something I keep running into: the error you were getting is probably because you also imported dplyr into your environment. If you would have used SparkR::first(SparkR::arrange(g, SparkR::desc(g$time))) things would probably have been fine (although obviously the query could've been more efficient).

Resources