I follow the guide:
https://cran.r-project.org/doc/FAQ/R-FAQ.html#How-do-I-convert-factors-to-numeric_003f
I have tried, without results:
Here it works:
x <- read.csv("https://data.covidstimuluswatch.org/prog.php?&detail=export_csv")[,3:5];
> str(x)
'data.frame': 10540 obs. of 3 variables:
$ Award.Date : int 20200514 20200514 20200514 20200514 20200514 20200514 20200514 20200514 20200514 20200514 ...
$ Award.Type : Factor w/ 2 levels "grant","loan": 1 1 1 1 1 1 1 1 1 1 ...
$ Grant.Amount: Factor w/ 9948 levels "$0","$1,000,090",..: 9157 6388 1280 6501 2141 4730 563 4999 6934 3373 ...
x[,3] <- as.numeric(gsub("[$,]","",x[,3]));
x <- x[(x[,1]>20200400)&x[,3]>0,];
x[,1] <- as.Date(as.character(x[,1]),"%Y%m%d");
x
And here it doesn't work:
srt(x) equals to srt(y) when using fread (..., stringsAsFactors = TRUE)
y<-fread("https://data.covidstimuluswatch.org/prog.php?&detail=export_csv",stringsAsFactors=TRUE)[,3:5];
str(y)
Classes ‘data.table’ and 'data.frame': 10540 obs. of 3 variables:
$ Award Date : int 20200514 20200514 20200514 20200514 20200514 20200514 20200514 20200514 20200514 20200514 ...
$ Award Type : Factor w/ 2 levels "grant","loan": 1 1 1 1 1 1 1 1 1 1 ...
$ Grant Amount: Factor w/ 9948 levels "$0","$1,000,090",..: 9157 6388 1280 6501 2141 4730 563 4999 6934 3373 ...
- attr(*, ".internal.selfref")=<externalptr>
> y[,gsub("[$,]","",.SD[1,3])]
[1] "9157"
> y[,factor(gsub("[$,]","",.SD[1,3]))]
[1] 9157
Levels: 9157
> y[,class(gsub("[$,]","",.SD[1,3]))]
[1] "character"
> y[,as.numeric(gsub("[$,]","",.SD[1,3]))]
[1] 9157
> y[1]
Award Date Award Type Grant Amount
1: 20200514 grant $852,780
> y[1,3]
Grant Amount
1: $852,780
> y[,as.numeric(paste(.SD[1,3])),]
[1] 9157
> y [,as.numeric(as.character(.SD[1,3])),]
[1] 9157
> y[,levels(gsub("[$,]","",.SD[1,3]))]
NULL
with the above result I can't apply:
More efficient, but harder to remember, is
as.numeric(levels(f))[as.integer(f)]
I can't translate the syntax to data.table
Any comments, help, ride is welcome,