我有一个像这样的数据框
TXT
我正在尝试将2小时的小时列与小时及其单位转换为2列。
我想要的输出
ID <- c("A","A","A","A","A","A","B","B","B","B","B","B")
Day <- c("Mon","Mon","Mon","Fri","Fri","Fri","Tue","Tue","Tue","Wed","Wed","Wed")
minute <- c(49,32,15,38,18,16,06,16,26,31,33,38)
second <- c(12,22,08,16,21,42,41,48,32,21,26,18)
hour0 <- c(0,0,0,60,0,0,0,0,0,0,0,0)
hour1 <- c(0,100,0,0,0,0,68,0,0,0,0,0)
hour2 <- c(0,0,0,0,0,0,0,92,0,0,0,72)
hour3 <- c(0,0,92,0,62,0,0,0,81,0,0,0)
hour4 <- c(110,0,0,0,0,0,0,0,0,93,0,0)
hour5 <- c(0,0,0,0,0,112,0,0,0,0,0,0)
hour6 <- c(0,0,0,0,0,0,0,0,0,0,105,0)
df <- data.frame(ID,Day,minute,second,hour0,hour1,hour2,hour3,hour4,hour5,hour6,
stringsAsFactors=FALSE)
我正在尝试以这种方式进行操作,但这并不是我想要的那样
ID Day minute second hour unit
1 A Mon 49 12 4 110
2 A Mon 32 22 1 100
3 A Mon 15 8 3 92
4 A Fri 38 16 0 60
5 A Fri 18 21 3 62
6 A Fri 16 42 5 112
7 B Tue 6 41 1 68
8 B Tue 16 48 2 92
9 B Tue 26 32 3 81
10 B Wed 31 21 4 93
11 B Wed 33 26 6 105
12 B Wed 38 18 2 72
有人可以指出我正确的方向吗?
答案 0 :(得分:1)
它可以与starts_with
或matches
匹配,而不是指定'hour0','hour1'等,然后在'unit'为0的行中filter
进行匹配。从“小时”(parse_number
)中提取数字部分
library(tidyverse)
df %>%
gather(hour, unit, starts_with("hour")) %>%
filter(unit != 0) %>%
mutate(hour = readr::parse_number(hour)) %>%
arrange(ID,
factor(Day, levels = c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")))