[英]R: Calculating new column (mean/median)
我想計算一列的平均值或中位數,但能夠 select 哪些值是根據另一列計算的。 (見下面的數據表)
僅計算百分比列的均值/中值似乎沒問題,但我在根據其他選擇執行此操作時遇到了一些麻煩。 例如,日期為“2014”的所有條目的百分比中位數。
將不勝感激有關如何執行此操作的任何建議。 如果這個問題在 SO 的其他地方得到了回答,我深表歉意,但我找不到它。
如果需要重現數據,我的代碼列在下面。
#Step 1: Load needed library
library(tidyverse)
library(rvest)
library(jsonlite)
library(stringi)
library(dplyr)
library(data.table)
library(ggplot2)
#Step 2: Access the URL of where the data is located
url <- "https://www.forsvarsbygg.no/ListApi/ListContent/78635/SoldEstates/0/10/"
#Step 3: Direct JSON as format of data in URL
data <- jsonlite::fromJSON(url, flatten = TRUE)
#Step 4: Access all items in API
totalItems <- data$TotalNumberOfItems
#Step 5: Summarize all data from API
allData <- paste0('https://www.forsvarsbygg.no/ListApi/ListContent/78635/SoldEstates/0/', totalItems,'/') %>%
jsonlite::fromJSON(., flatten = TRUE) %>%
.[1] %>%
as.data.frame() %>%
rename_with(~str_replace(., "ListItems.", ""), everything())
#Step 6: removing colunms not needed
allData <- allData[, -c(1,4,8,9,11,12,13,14,15)]
#Step 7: remove whitespace and change to numeric in columns SoldAmount and Tax
#https://stackoverflow.com/questions/71440696/r-warning-argument-is-not-an-atomic-vector-when-attempting-to-remove-whites/71440806#71440806
allData[c("Tax", "SoldAmount")] <- lapply(allData[c("Tax", "SoldAmount")], function(z) as.numeric(gsub(" ", "", z)))
#Step 8: Remove rows where value is NA
#https://stackoverflow.com/questions/4862178/remove-rows-with-all-or-some-nas-missing-values-in-data-frame
alldata <- allData %>%
filter(across(where(is.numeric),
~ !is.na(.)))
#Step 9: Remove values below 10000 NOK on SoldAmount og Tax.
alldata <- alldata %>%
filter_all(any_vars(is.numeric(.) & . > 10000))
#Step 10: Calculate percentage change between tax and sold amount and create new column with percent change
#df %>% mutate(Percentage = number/sum(number))
alldata_Percent <- alldata %>% mutate(Percentage = (SoldAmount-Tax)/Tax)
你只是在尋找group_by
並從dplyr
summarize
?
alldata_Percent %>%
group_by(Date) %>%
summarize(median_percent = median(Percentage),
mean_percent = mean(Percentage))
## A tibble: 15 x 3
#> Date median_percent mean_percent
#> <chr> <dbl> <dbl>
#> 1 1970 0 1.98
#> 2 2003 0 -0.0345
#> 3 2004 0 0.141
#> 4 2005 0.0723 0.156
#> 5 2006 0.0132 0.204
#> 6 2007 0.024 0.131
#> 7 2008 0 -0.00499
#> 8 2009 0.0247 0.0769
#> 9 2010 0.0340 0.0422
#> 10 2011 0 0.155
#> 11 2012 0 0.0103
#> 12 2013 0 0.0571
#> 13 2014 0 0.0352
#> 14 2015 0 0.0646
#> 15 2016 0 -0.0195
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.