小编Roy*_*tty的帖子

在 for 循环中使用条件的最快方法

因此,对于数据集birthwt,我想要母亲吸烟且分娩时未满 20 岁的低体重婴儿的百分比。换句话说,我想要 <2600 的 bwt(重量)是 <20 岁且烟雾 == 1。

我运行接下来的三段代码,它们实际上给了你正确的答案:

 # new df with the conditions
new_df <- subset(birthwt, age<20 & smoke==1)

 #for loop to calculate the low weight

low_weight <- 0
for (i in 1:length(new_df$bwt)){
  if(bwt[i] < 2600){
    low_weight <- low_weight + 1
  }
}

 #low weight for the original dataset
low_weight_tot <- 0
attach(birthwt)
for (i in 1:length(birthwt$bwt)){
  if(bwt[i] < 2600){
    low_weight_tot <- low_weight_tot + 1
  }
}

print(low_weight/low_weight_tot)*100
Run Code Online (Sandbox Code Playgroud)

但我觉得它很乏味,有没有其他更简单的方法可以用循环来做到这一点?

谢谢!

loops for-loop r

2
推荐指数
1
解决办法
82
查看次数

在 R 中的向量中选择偶数的函数

我想创建一个函数,给定一个向量,用偶数报告另一个向量。

evens <- function(x){
  vector <- c()
  for (i in 1:length(x)){
    if (i %% 2 == 0){
      vector[i] <- vector[i] + i
    }
  }
  vector
}
Run Code Online (Sandbox Code Playgroud)

但这给出 NULL了 x 中的一个数字。

有人知道缺少什么吗?谢谢

for-loop r function

2
推荐指数
2
解决办法
4448
查看次数

将正态曲线叠加到 ggplot2 中的直方图

我想为具有正态分布的名为“Dist”的向量绘制直方图,并用总体参数覆盖正态曲线。我在 stackoverflow 中找到了几篇关于同一主题的帖子,但没有找到我收到的错误消息。

plot1 <-ggplot(data = dist) + 
  geom_histogram(mapping = aes(x = dist), fill="steelblue", colour="black", binwidth = 1) +
  ggtitle("Frequences")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我已经尝试了几件事来向先前的图添加正态曲线:

首先,将一个函数添加到直方图块代码中,并具有所需的值:

stat_function(fun = dnorm, args = list(mean = mu2, sd = sd2))
Run Code Online (Sandbox Code Playgroud)

但是这段代码不会向情节添加任何内容。结果是一样的,只是直方图。

而且,创建一条曲线并将其添加到绘图中。

#Create the curve data
x <- seq(8, 24, length.out=100)
y <- with(dist, data.frame(x = x, y = dnorm(x, mean(mu2), sd(sd2))))

#add the curve to the base plot
plot1 + geom_line(data = y, aes(x = x, y = y), color = "red")
Run Code Online (Sandbox Code Playgroud)

这给了我下一条错误消息:

删除了 100 行包含缺失值 …

overlay r ggplot2

1
推荐指数
1
解决办法
1605
查看次数

标签 统计

r ×3

for-loop ×2

function ×1

ggplot2 ×1

loops ×1

overlay ×1