Reputation: 149
I am reading an api using R and was able to retrieve the data, however, the data itself is retrieved in JSON format with what seems to be in 3 sections.
Converting the json data to a df using
fromJSON(data)
It was successful.
The next step was to drop the unnecessary columns, which is the my current issue and not able drop any columns to which I just recently found out how the data is formatted in the data frame.
lead <- GET("some api", add_headers(Authorization="Bearer some apikey"))
data <- content(lead,"text") #display the data looks something like below
The data seems to be formatted into 3 sections where I believe the issue is preventing columns to be dropped
$'data'
$included
$link
I've looked at multiple stackoverflow posts and r guides on dropping column name in df, but was unsuccessful
> df <- df[,-1]
Error in df[, -1] : incorrect number of dimensions
> df <- subset(df, select = -c("$'data'$id"))
Error in subset.default(df, select = -c("$'data'$id")) :
argument "subset" is missing, with no default
The end goal is to drop everything in $links, a few columns in $included, and a few columns in $data
Upvotes: 0
Views: 328
Reputation: 370
Completely remove links
:
df$links <- NULL
Remove columns 1 and 2 from included
:
df$included[,c(1, 2)] <- NULL
Remove columns 3 and 4 from data
:
df$data[,c(3, 4)] <- NULL
For a working example, see below with iris and mtcars:
exr <- list(iris = iris, mtcars = mtcars)
head(exr$mtcars)
| | mpg| cyl| disp| hp| drat| wt| qsec| vs| am| gear| carb|
|:-----------------|----:|---:|----:|---:|----:|-----:|-----:|--:|--:|----:|----:|
|Mazda RX4 | 21.0| 6| 160| 110| 3.90| 2.620| 16.46| 0| 1| 4| 4|
|Mazda RX4 Wag | 21.0| 6| 160| 110| 3.90| 2.875| 17.02| 0| 1| 4| 4|
|Datsun 710 | 22.8| 4| 108| 93| 3.85| 2.320| 18.61| 1| 1| 4| 1|
|Hornet 4 Drive | 21.4| 6| 258| 110| 3.08| 3.215| 19.44| 1| 0| 3| 1|
|Hornet Sportabout | 18.7| 8| 360| 175| 3.15| 3.440| 17.02| 0| 0| 3| 2|
|Valiant | 18.1| 6| 225| 105| 2.76| 3.460| 20.22| 1| 0| 3| 1|
exr$mtcars[,c(1,2)] <- NULL
head(exr$mtcars)
| | disp| hp| drat| wt| qsec| vs| am| gear| carb|
|:-----------------|----:|---:|----:|-----:|-----:|--:|--:|----:|----:|
|Mazda RX4 | 160| 110| 3.90| 2.620| 16.46| 0| 1| 4| 4|
|Mazda RX4 Wag | 160| 110| 3.90| 2.875| 17.02| 0| 1| 4| 4|
|Datsun 710 | 108| 93| 3.85| 2.320| 18.61| 1| 1| 4| 1|
|Hornet 4 Drive | 258| 110| 3.08| 3.215| 19.44| 1| 0| 3| 1|
|Hornet Sportabout | 360| 175| 3.15| 3.440| 17.02| 0| 0| 3| 2|
|Valiant | 225| 105| 2.76| 3.460| 20.22| 1| 0| 3| 1|
Upvotes: 1