I honestly don't think that what I want to do is that difficult. However, I've been beating my head against this issue for several hours without finding a solution, so I guess I'll ask for help.
I need to add a new row to a tibble, The newly-added row will contain the sums of some, but not all, of the columns in the tibble.
https://stackoverflow.com/questions/33565949/add-row-to-data-frame-with-dplyr, suggests this code snippet:
"mydata %>%
rbind(list(c("00000", "Region Total", sum(GDP),sum(Percent))))"
However, I receive the error message "Error in xi[[j]] : subscript out of bounds"
Thanks in advance for your help.
This is my starting tibble:
FIPS | County | GDP | Percent | |
---|---|---|---|---|
1 | 29007 | Audrain | 698358 | 0.5 |
2 | 29019 | Boone | 7521903 | 4.5 |
3 | 29027 | Callaway | 1456387 | -3.2 |
4 | 29029 | Camden | 1152673 | -1.1 |
This is my desired output containing the new row #5, which contains observations for the 2 character variables (FIPS, County) and the sums of the two numeric variables (GDP, Percent):
FIPS | County | GDP | Percent | |
---|---|---|---|---|
1 | 29007 | Audrain | 698358 | 0.5 |
2 | 29019 | Boone | 7521903 | 4.5 |
3 | 29027 | Callaway | 1456387 | -3.2 |
4 | 29029 | Camden | 1152673 | -1.1 |
5 | 00000 | Region Total | 10829321 | 0.7 |
FIPS <- c("29007", "29019", "29027", "29029")
County <- c("Audrain", "Boone", "Callaway", "Camden")
GDP <- c(698358, 7521903, 1456387, 1152673)
Percent <- c(0.5, 4.5, -3.2, -1.1)
mydata <- cbind.data.frame(FIPS, County, GDP, Percent)
mydata <-as_tibble(data)
mydata$FIPS <- as.character(mydata$FIPS)
mydata$County <- as.character(mydata$County)
class(mydata$FIPS)
class(mydata$County)
class(mydata$GDP)
class(mydata$Percent)
# suggested by https://stackoverflow.com/questions/33565949/add-row-to-data-frame-with-dplyr
mydata %>%
rbind(list(c("00000", "Region Total", sum(GDP),sum(Percent))))
#error: Error in xi[[j]] : subscript out of bounds