这个问题在这里已经有了答案:
Reshaping multiple sets of measurement columns (wide format) into single columns (long format)
(8 个回答)
3年前关闭。
我有一个这样的数据框:
structure(list(one = structure(1:4, .Label = c("a", "b", "c",
"d"), class = "factor"), two = c(2, 4, 7, 3), x.1 = c("x1a",
"x1b", "x1c", "x1d"), x.2 = c("x2a", "x2b", "x2c", "x2d"), x.3 = c("x3a",
"x3b", "x3c", "x3d"), y.1 = c(NA, "y1b", "y1c", NA), y.2 = c(NA,
"y2b", "y2c", NA), y.3 = c(NA, "y3b", "y3c", NA)), .Names = c("one",
"two", "x.1", "x.2", "x.3", "y.1", "y.2", "y.3"), row.names = c(NA,
-4L), class = "data.frame")
如您所见,每个事件 a、b、c 和 d(变量“一”)的观察值存储为列,其中 x 和 y 定义单独的观察值,1、2 和 3 定义变量。变量“二”在这里没有意义。
我喜欢 reshape 这个数据框,使其整洁,每个观察都有自己的行,每个变量都有自己的列。
最终的数据框应如下所示:
structure(list(one = structure(c(1L, 2L, 2L, 3L, 3L, 4L), .Label = c("a",
"b", "c", "d"), class = "factor"), two = c(2, 4, 2, 7, 5, 3),
var1 = c("x1a", "x1b", "y1b", "x1c", "y1c", "x1d"), var2 = c("x2a",
"x2b", "y2b", "x2c", "y2c", "x2d"), var3 = c("x3a", "x3b",
"y3b", "x3c", "y3c", "x3d")), .Names = c("one", "two", "var1",
"var2", "var3"), row.names = c(1L, 2L, 5L, 3L, 6L, 4L), class = "data.frame")
我对 reshape 包中的 cast 和 melt 功能有点熟悉,但还没有找到一种以智能方式 reshape DF 的方法。
现在,以下提供了我已经达到的状态:
df.between <- melt(df.in, id.vars=c("one", "two"))
df.between$variable <- gsub("x.|y.", "", df.between$variable)
现在“变量”列确实正确识别了变量(1、2 或 3)。但是,我无法将其转换为所需的形式,并且由于使用了
grepl
,因此该解决方案似乎对更大的数据集没有用处。 .很高兴在这里向正确的方向轻推。
最佳答案
我们可以使用melt
来自 data.table
的开发版本即v1.9.5
,可以处理多个patterns
对于measure
变量。
library(data.table)
melt(setDT(df1), measure=patterns('.1', '.2', '.3'),
na.rm=TRUE, value.name=paste0('var', 1:3))[, variable:=NULL][order(one)]
# one two var1 var2 var3
#1: a 2 x1a x2a x3a
#2: b 4 x1b x2b x3b
#3: b 4 y1b y2b y3b
#4: c 7 x1c x2c x3c
#5: c 7 y1c y2c y3c
#6: d 3 x1d x2d x3d
编辑:我们不需要
c
里面patterns
它还将提供完全匹配(来自@Jaap 的评论)。
关于r - 如何将多列转换为观察值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32655356/