我目前正在使用R中的数据框,这是一个“水平”结构。以下是所涉及数据的示例:
head(all[,1:4])
Variable Channel TIMEPERIOD Volume
V1 Retail 41640 50
V1 Retail 41671 60
V1 Retail 41699 40
V1 Retail 41730 30
V1 Retail 41760 30
V1 Retail 41791 40
在上面的数据中,'Volume'变量是数据框中约50个附加变量/列中的第一个。我的预期输出是:
head(all[,1:5])
Variable Channel TIMEPERIOD Variable Value
V1 Retail 41640 Volume 50
V1 Retail 41671 Volume 60
V1 Retail 41699 Volume 40
V1 Retail 41730 Volume 30
V1 Retail 41760 Volume 30
V1 Retail 41791 Volume 40
有没有比插入空白变量列并逐列手动浏览数据框更快捷的方法?我过去做过这个:
# Create subset of specific columns
volume <- subset(nielsen_retail, select = c("X__1", "X__2",
"X__3"))
# Rename columns
colnames(volume) <- c("prod_name", "time_period", "value")
# Insert channel column
volume$channel <- "retail"
# Insert variable column
volume$variable <- "sales_volume"
# Reorder columns
volume <- volume[ , c("prod_name","time_period",
"channel","variable", "value")]
正如您所看到的,这会导致在大型数据框中进行非常手动且耗时的过程。在此先感谢您的帮助!