更改数据格式

Change the format of your data

对于你们中的一些人来说,这是一个简单的问题;我想重塑我的数据

我的数据结构:

structure(list(Time = c("00:01", "00:02", "00:03", "00:04", "00:05", 
"00:06", "00:07", "00:08", "00:09", "00:10"), Week_Day = c("Wednesday", 
"Wednesday", "Wednesday", "Wednesday", "Wednesday", "Wednesday", 
"Wednesday", "Wednesday", "Wednesday", "Wednesday"), Value = c(4.293333, 
4.293333, 6.708333, 6.171667, 5.635, 5.098333, 5.098333, 5.098333, 
5.098333, 4.293333), Week_Day = c("Thursday", "Thursday", "Thursday", 
"Thursday", "Thursday", "Thursday", "Thursday", "Thursday", "Thursday", 
"Thursday"), Value = c(2.415, 1.878333, 1.878333, 1.878333, 1.878333, 
1.878333, 1.878333, 1.878333, 1.878333, 1.878333), Week_Day = c("Friday", 
"Friday", "Friday", "Friday", "Friday", "Friday", "Friday", "Friday", 
"Friday", "Friday"), Value = c(4.025, 4.293333, 4.293333, 4.293333, 
3.756667, 3.756667, 3.756667, 4.293333, 4.83, 4.83), Week_Day = c("Saturday", 
"Saturday", "Saturday", "Saturday", "Saturday", "Saturday", "Saturday", 
"Saturday", "Saturday", "Saturday"), Value = c(14.758333, 10.196667, 
4.561667, 4.293333, 4.83, 5.098333, 4.83, 4.83, 5.366667, 4.561667
), Week_Day = c("Sunday", "Sunday", "Sunday", "Sunday", "Sunday", 
"Sunday", "Sunday", "Sunday", "Sunday", "Sunday"), Value = c(5.098333, 
4.83, 5.098333, 4.83, 4.025, 4.025, 4.293333, 4.293333, 4.293333, 
4.293333), index = 1:10), row.names = c(NA, 10L), class = "data.frame")

初始数据格式为

"Time"     "Week_Day" "Value"    "Week_Day" "Value"    "Week_Day" "Value"    "Week_Day" "Value"    "Week_Day" "Value"    "index"  

哎呀我可以把这个格式改成

"Time" "Week_Day" "Value" "Index"

非常感谢

使用data.table:

library(data.table)
setDT(data)
data_long <- melt(
  data, 
  id.vars = c("Time", "index"), 
  measure.vars = patterns(Week_Day = "Week_Day", Value = "Value")
)[, !"variable"]

 head(data_long)
    Time index  Week_Day    Value
1: 00:01     1 Wednesday 4.293333
2: 00:02     2 Wednesday 4.293333
3: 00:03     3 Wednesday 6.708333
4: 00:04     4 Wednesday 6.171667
5: 00:05     5 Wednesday 5.635000
6: 00:06     6 Wednesday 5.098333

# To convert back to a regular data.frame:
setDF(data_long)

基地 R:

data_long <- data.frame(
  Time = data$Time,
  index = data$index,
  Week_Day = unlist(data[names(data) == "Week_Day"]),
  Value = unlist(data[names(data) == "Value"]),
  row.names = NULL
)

head(data_long)
   Time index  Week_Day    Value
1 00:01     1 Wednesday 4.293333
2 00:02     2 Wednesday 4.293333
3 00:03     3 Wednesday 6.708333
4 00:04     4 Wednesday 6.171667
5 00:05     5 Wednesday 5.635000
6 00:06     6 Wednesday 5.098333