根据澳大利亚的边际税率,我正在编写一个函数,根据收入水平计算欠税.
我写了一个函数的简单版本,使用以下内容产生正确的税额:
income_tax <- function(income) {
# Calculate income tax liability based on income
#
# Returns the amount of income tax owed
if (income > 0 & income <= 18200) {
tax <- 0
} else if (income > 18200 & income <= 37000) {
tax <- (income - 18200) * .19
} else if (income > 37000 & income <= 80000) {
tax <- 3572 + (income - 37000) * .325
} else if (income > …Run Code Online (Sandbox Code Playgroud) 我有一系列的ggplot图表,我正在重复一些小的变化.我想将这些qplots的选项包装成一个函数,以避免代码中的大量重复.
我的问题是,对于某些图表,我使用的是+ facet_wrap()选项,但对于其他图表,我不是.即我需要facet wrap作为可选参数.当包含它时,代码需要使用facets参数中提供的变量调用+ facet_wrap().
理想情况下,我的函数看起来像这样,facet是一个可选参数:
$ qhist(variable, df, heading, facets)
Run Code Online (Sandbox Code Playgroud)
我已经尝试使用谷歌搜索如何添加可选参数,他们建议传递一个默认值或使用带有missing()函数的if循环.我无法上班.
这是我编写的函数,包含了可选facet参数的所需功能.
$ qhist <- function(variable, df, heading, facets) {
qplot(variable, data = df, geom = "histogram", binwidth = 2000,
xlab = "Salary", ylab = "Noms") +
theme_bw() +
scale_x_continuous(limits=c(40000,250000),
breaks=c(50000,100000,150000,200000,250000),
labels=c("50k","100k","150k","200k","250k")) +
opts(title = heading, plot.title = theme_text(face = "bold",
size = 14), strip.text.x = theme_text(size = 10, face = 'bold'))
# If facets argument supplied add the following, else do not add this code
+ facet_wrap(~ facets)
Run Code Online (Sandbox Code Playgroud) 当使用dplyr tbl_df数据帧进行子设置时,我发现了一些奇怪的行为.当我使用'matrix' style df[,'a']它对数据帧进行子集时,它会按预期返回一个向量.但是,当我在tbl_df数据框中执行相同操作时,它会返回数据框.
我使用Iris数据集在下面复制了它.
有人可以解释为什么会发生这种情况,或者我如何解决数据帧的问题?我需要在构建中使用dplyr和readr来需要这种行为.
library(dplyr)
data(iris)
str(iris['Sepal.Length'])
'data.frame': 150 obs. of 1 variable:
$ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
str(iris[,'Sepal.Length'])
num [1:150] 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
iris <- tbl_df(iris)
str(iris[,'Sepal.Length'])
Classes ‘tbl_df’ and 'data.frame': 150 obs. of 1 variable:
$ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
Run Code Online (Sandbox Code Playgroud) 我正在尝试比较R中的两个时间序列,以通过将它们绘制在折线图上来评估它们之间的相关程度。为了避免为数据使用两个单独的轴,我想为每个值创建索引,以通过绘制索引而不是原始数据来绘制自日期X以来的值变化。
数据如下所示:
Table 1.
Month A B
Jan 3883 151831
Feb 3626 154070
Mar 4346 163550
Apr 3439 155674
Run Code Online (Sandbox Code Playgroud)
所需的输出如下所示:
Table 2.
Month A A.index B B.index
Jan 3883 100 151831 100
Feb 3626 93.38 154070 101.47
Mar 4346 111.92 163550 107.71
Apr 3439 88.56 155674 102.53
Run Code Online (Sandbox Code Playgroud)
I can achieve this in excel by exporting table 1 to excel and adding a column for A.index and B.index and using a calculation to determine the change from the the index number …