让我首先说欢迎使用 stackoverflow。很高兴有新用户。当您提出问题时,提供您正在使用的代码和看起来像原始数据的可重现数据集对您很有帮助并受到鼓励。这称为最小可重现示例。要在此处获取数据集,您可以使用多个选项,这里有两个:使用 dput()
对象名称并剪切和粘贴控制台中显示的内容,或者直接发布数据框。对于代码,请提供复制您的问题所需的所有代码。我希望这对您将来提出的问题有所帮助。
我可能不完全理解,但我认为您想要转换而不是转置数据。
dat <- data.frame(market=rnorm(10), date=rnorm(10), #let's create a data set
sitename=rnorm(10), impression=rnorm(10), clicks=rnorm(10))
dat #look at it (I pasted it below)
# > dat
# market date sitename impression clicks
# 1 -0.9593797 -0.08411994 1.6079129 -0.5204772 -0.31633966
# 2 -0.5088689 1.78799500 -0.2469315 1.3476964 -0.04344779
# 3 -0.1527465 0.81673996 1.7824969 -1.5531260 -1.28304384
# 4 -0.7026194 0.52072913 -0.1174356 0.5722210 -1.20474443
# 5 -0.4537490 -0.69139062 1.1124277 -0.2452974 -0.33025320
# 6 0.7466588 0.36318337 -0.4623319 -0.9036768 -0.65754302
# 7 0.8007612 2.59588554 0.1820732 0.4318629 -0.36308748
# 8 1.0781715 -1.01512734 0.2297475 0.9219439 -1.15687902
# 9 0.3731450 -0.19004572 0.5190749 -1.4020371 -0.97370295
# 10 0.7724259 1.76528303 0.5781786 -0.5490849 -0.83819036
#now to create the new columns (I think this is what you want)
#the easiest way is to use transform. ?tranform for more
dat.new <- transform(dat, sitename.clicks=sitename-clicks,
impression.clicks=impression-clicks)
dat.new #here's the new data set. Notice it has the new and old columns.
#To get rid of the old columns you can use indexing and specify the columns you want.
dat.new[, c(1:2, 6:7)]
#We could have also done:
dat.new[, c(1,2,6,7)]
#or said the columns not wanted with negative indexing:
dat.new[, -c(3:5)]
编辑在查看布赖恩的评论和变量时,我认为从长到宽的转变是张贴者想要的。我也可能会使用 Wickham 的 reshape2 包来处理它,因为这种方法对我来说更容易使用,而且我想它对 R 初学者来说也会更容易。但是,这是使用 Brian 提供的相同数据集进行长到宽格式的基本方法:
wide <- reshape(DF, v.names=c("impression", "clicks"), idvar=c("market", "date"),
timevar="sitename", direction="wide")
reshape(wide)
reshape 功能非常灵活,但需要一些时间来适应正确使用。我也将保留我之前的回复以保留这篇文章的历史,尽管我现在相信这不是发帖者的意图。它提醒您,一个可重现的示例对于提供清晰的查询非常有帮助。