0

R に次の形式の大きなデータフレームがあります。

"SubjID"    "HR"    "IBI"   "Stimulus"  "Status"
"S1"    75.98   790 1   1
"S1"    75.95   791 1   2
"S1"    65.7    918 1   3
"S1"    59.63   100 1   4
"S1"    59.44   101 1   5
"S1"    59.62   101 2   1
"S1"    63.85   943 2   2
"S1"    60.75   992 2   3
"S1"    59.62   101 2   4
"S1"    61.68   974 2   5
"S2"    65.21   921 1   1
"S2"    59.23   101 1   2
"S2"    61.23   979 1   3
"S2"    70.8    849 1   4
"S2"    74.21   809 1   4

ステータス列の値ごとに「HR」列の平均をプロットしたいと思います。

次の R コードを作成し、データのサブセットを ("Status" の異なる値で) 作成してプロットします。

numberOfSeconds <- 8;

    for(stimNumber in 1:40) {

    stimulus2plot <- subset(resampledDataFile, Stimulus == stimNumber & Status <= numberOfSeconds, select=c(SubjID, HR, IBI, Stimulus, Status))

    plot(stimulus2plot$HR~stimulus2plot$Status, xlab="",ylab="")
    lines(stimulus2plot$HR~stimulus2plot$Status, xlab="",ylab="")

    }

したがって、次のようなプロットが得られます。ここに画像の説明を入力

「刺激」ごとに1つのプロットがあります。各プロットの X 軸には「ステータス」列があり、YI には「SubjID」ごとに 1 つの「HR」値があります。もうすぐそこ...

ただし、最終的に取得したいのは、各 X 値ごとに 1 つの Y データポイントです。つまり、Y は次のプロットのように平均値 (HR 列の平均) である必要があります。

ここに画像の説明を入力

これはどのように達成できますか?各データポイントにエラーバーとして表示される標準偏差もあると便利です。

よろしくお願いします。

4

4 に答える 4

2

必要なものに最も近づけるには:

library(ggplot2)
library(plyr)
df.summary <- ddply(df, .(Stimulus, Status), summarise,
                    HR.mean = mean(HR),
                    HR.sd = sd(HR))
ggplot(df.summary, aes(Status, HR.mean)) + geom_path() + geom_point() + 
  geom_errorbar(aes(ymin=HR.mean-HR.sd, ymax=HR.mean+HR.sd), width=0.25) +facet_wrap(~Stimulus) 

ここに画像の説明を入力

于 2013-03-12T12:03:08.323 に答える
2

最も簡単にできることは、最初に値を事前計算してからプロットすることです。私はddplyこの種の分析に使用します:

library(plyr)
res = ddply(df, .(Status), summarise, mn = mean(HR))

ggplot2 を使用してプロットします。

ggplot(res, aes(x = Status, y = mn)) + geom_line() + geom_point()
于 2013-03-12T11:53:50.733 に答える
2

それを行う最も簡単な方法は、tapply(). あなたのdata.frame場合data

means <- with(data, tapply(HR, Status, mean))
plot(means, type="l")

エラーバーの計算とプロットも簡単です。

serr <- with(data, tapply(HR, Status, function(x)sd(x)/sqrt(length(x))))
plot(means, type="o", ylim=c(50,80))
sapply(1:length(serr), function(i) lines(rep(i,2), c(means[i]+serr[i], means[i]-serr[i])))
于 2013-03-12T11:54:46.617 に答える
0

次の偽のデータの例をガイドとして使用して、次のように ggplot2 内でこれを完全に行うことができます。

DF <- data.frame(stimulus = factor(rep(paste("Stimulus", seq(4)), each = 40)),
                 subject = factor(rep(seq(20), each = 8)),
                 time = rep(seq(8), 20),
                 resp = rnorm(160, 50, 10))
# spaghetti plots
ggplot(DF, aes(x = time, y = resp, group = subject)) +
   geom_line() +
   facet_wrap(~ stimulus, ncol = 1)
# plot of time averages by stimulus
ggplot(DF, aes(x = time, y = resp)) +
   stat_summary(fun.y = mean, geom = "line", group = 1) +
   stat_summary(fun.y = mean, geom = "point", group = 1, shape = 1) +
   facet_wrap(~ stimulus, ncol = 1)
于 2013-03-14T08:53:54.423 に答える