将时间表(宽格式)转换为 R 中的长格式并且 select 只有一些行
Convert a schedule (in wide form) to long form in R and select only some rows
我想为级别和日期的每个组合创建行,其中有 "X"。
示例:
dat <- data.frame(1:5, matrix( c("X", "-", "X", "-", "-", "X", "X", "-", "X", "-", "X", "-", "X", "-", "X", "-", "X", "-", "-", "-", "-", "-", "X", "X", "-"), 5, 5, byrow=T))
colnames(dat) <- c("lvl", "Mon", "Tues", "Wed", "Thur", "Fri" )
如果您的时间表存储为矩阵或数据框,您可以使用 reshape2
包:
# generate a fake schedule
sched <- matrix(rbinom(25, 1, 1/2), 5,
dimnames = list(1:5, c("Mo", "Tu", "We", "Th", "Fr")))
library(reshape2)
melt(sched)
# Var1 Var2 value
# 1 1 Mo 0
# 2 2 Mo 0
# 3 3 Mo 1
# 4 4 Mo 0
# 5 5 Mo 1
# 6 1 Tu 0
# 7 2 Tu 1
# 8 3 Tu 1
# 9 4 Tu 0
# 10 5 Tu 1
# 11 1 We 1
# 12 2 We 1
# 13 3 We 1
# 14 4 We 0
# 15 5 We 0
# 16 1 Th 0
# 17 2 Th 1
# 18 3 Th 1
# 19 4 Th 0
# 20 5 Th 0
# 21 1 Fr 0
# 22 2 Fr 1
# 23 3 Fr 1
# 24 4 Fr 1
# 25 5 Fr 1
包tidyr
中也有函数gather
,但它只适用于数据帧,总体上更高级一些。
要仅获取 value
列中带有 1
的行,请执行:
sched <- melt(sched)
sched[sched$value == 1, ]
我想为级别和日期的每个组合创建行,其中有 "X"。
示例:
dat <- data.frame(1:5, matrix( c("X", "-", "X", "-", "-", "X", "X", "-", "X", "-", "X", "-", "X", "-", "X", "-", "X", "-", "-", "-", "-", "-", "X", "X", "-"), 5, 5, byrow=T))
colnames(dat) <- c("lvl", "Mon", "Tues", "Wed", "Thur", "Fri" )
如果您的时间表存储为矩阵或数据框,您可以使用 reshape2
包:
# generate a fake schedule
sched <- matrix(rbinom(25, 1, 1/2), 5,
dimnames = list(1:5, c("Mo", "Tu", "We", "Th", "Fr")))
library(reshape2)
melt(sched)
# Var1 Var2 value
# 1 1 Mo 0
# 2 2 Mo 0
# 3 3 Mo 1
# 4 4 Mo 0
# 5 5 Mo 1
# 6 1 Tu 0
# 7 2 Tu 1
# 8 3 Tu 1
# 9 4 Tu 0
# 10 5 Tu 1
# 11 1 We 1
# 12 2 We 1
# 13 3 We 1
# 14 4 We 0
# 15 5 We 0
# 16 1 Th 0
# 17 2 Th 1
# 18 3 Th 1
# 19 4 Th 0
# 20 5 Th 0
# 21 1 Fr 0
# 22 2 Fr 1
# 23 3 Fr 1
# 24 4 Fr 1
# 25 5 Fr 1
包tidyr
中也有函数gather
,但它只适用于数据帧,总体上更高级一些。
要仅获取 value
列中带有 1
的行,请执行:
sched <- melt(sched)
sched[sched$value == 1, ]