[英]How transform grouping variable to columns in R?
I used the follwoing dataset我使用了以下数据集
data.frame(Group=c("A","A","A","B","B","B"),
time= c("10:30","10:45","10:15","10:30","10:20","10:15"),
value= c(1,2,3,1,5,6))
and want to get the following table并想得到下表
I tried dcast() function from reshape2 package, but did not figure out how split Group variable based on time and value variables.我尝试了来自 reshape2 package 的 dcast() function,但没有弄清楚如何根据时间和值变量拆分 Group 变量。 Could you help?
你能帮忙吗?
library(reshape2)
dcast(df, time + value ~ paste0("group", Group), value.var = "Group")
# time value groupA groupB
# 1 10:15 3 A <NA>
# 2 10:15 6 <NA> B
# 3 10:20 5 <NA> B
# 4 10:30 1 A B
# 5 10:45 2 A <NA>
Try this:试试这个:
library(dplyr)
library(tidyr)
#Code
new <- df %>%
mutate(Val=paste0('Group',Group)) %>%
pivot_wider(names_from = Val,values_from=Group)
Output: Output:
# A tibble: 5 x 4
time value GroupA GroupB
<chr> <dbl> <chr> <chr>
1 10:30 1 A B
2 10:45 2 A NA
3 10:15 3 A NA
4 10:20 5 NA B
5 10:15 6 NA B
Update: Using new data:更新:使用新数据:
#Code 2
df %>%
mutate(id=row_number(),
Val=paste0('Group',Group)) %>%
pivot_wider(names_from = Val,values_from=Group) %>% select(-id)
Output: Output:
# A tibble: 7 x 4
time value GroupA GroupB
<chr> <dbl> <chr> <chr>
1 10:30 1 A NA
2 10:30 1 A NA
3 10:45 2 A NA
4 10:15 3 A NA
5 10:30 1 NA B
6 10:20 5 NA B
7 10:15 6 NA B
A base R option using reshape
使用
reshape
的基础 R 选项
reshape(
transform(
df,
grpName = paste0("Group", Group)
),
direction = "wide",
idvar = c("time", "value"),
timevar = "grpName"
)
which gives这使
time value Group.GroupA Group.GroupB
1 10:30 1 A B
2 10:45 2 A <NA>
3 10:15 3 A <NA>
5 10:20 5 <NA> B
6 10:15 6 <NA> B
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.