我在" long"中有一个数据集。格式,我想改变为"宽"格式。我想按一组列进行分组,并将剩余的列分组到相应的对中。我想我知道当只有一个列被加宽时,如何长到宽,但是当我需要同时多个加宽时,我无法使它工作。
请查看所需起点和终点的示例。
开始:
structure(list(gender = structure(c(2L, 2L, 2L, 1L, 1L, 1L, 2L
), .Label = c("female", "male"), class = "factor"), state = structure(c(3L,
3L, 3L, 1L, 1L, 1L, 2L), .Label = c("ca", "ny", "tx"), class = "factor"),
name = structure(c(3L, 5L, 7L, 6L, 1L, 2L, 4L), .Label = c("ashley",
"jackie", "john", "luke", "mark", "mary", "rob"), class = "factor"),
value = c(1L, 2L, 3L, 1L, 2L, 3L, 1L)), .Names = c("gender",
"state", "name", "value"), class = "data.frame", row.names = c(NA,
-7L))
ENDING:
structure(list(gender = structure(c(2L, 1L, 2L), .Label = c("female",
"male"), class = "factor"), state = structure(c(3L, 1L, 2L), .Label = c("ca",
"ny", "tx"), class = "factor"), value1 = c(1L, 1L, 1L), name1 = structure(c(1L,
3L, 2L), .Label = c("john", "luke", "mary"), class = "factor"),
value2 = c(2L, 2L, NA), name2 = structure(c(2L, 1L, NA), .Label = c("ashley",
"mark"), class = "factor"), value3 = c(3L, 3L, NA), name3 = structure(c(2L,
1L, NA), .Label = c("jackie", "rob"), class = "factor")), .Names = c("gender",
"state", "value1", "name1", "value2", "name2", "value3", "name3"
), class = "data.frame", row.names = c(NA, -3L))
答案 0 :(得分:1)
我们可以使用dcast
中的data.table
,data.frame
可以使用多个' value.var'列。我们将data.table
转换为setDT(df1)
(dcast
),创建一个序列列(" N"),按"性别"分组。和"州"。然后,使用library(data.table)
setDT(df1)[, N:= 1:.N, .(gender,state)]
dcast(df1, gender+state~N, value.var=c("name", "value"), sep="")
# gender state name1 name2 name3 value1 value2 value3
#1: female ca mary ashley jackie 1 2 3
#2: male ny luke NA NA 1 NA NA
#3: male tx john mark rob 1 2 3
转换“长”字样。广泛的'格式。
reshape
创建序列列
后,也可以使用base R
中的dfN <- transform(df1, N = ave(seq_along(state),
gender, state, FUN=seq_along))
reshape(dfN, idvar=c('gender', 'state'), timevar= 'N',
direction='wide')
# gender state name.1 value.1 name.2 value.2 name.3 value.3
#1 male tx john 1 mark 2 rob 3
#4 female ca mary 1 ashley 2 jackie 3
#7 male ny luke 1 <NA> NA <NA> NA
来完成此操作
add_filter("retrieve_password_message", function ($message, $key) {
// modify the message with your code here
return $message;
}, 10, 2);