使用reshape / cast r时创建多个变量

时间:2017-12-13 15:26:17

标签: r casting reshape

我正在处理调查数据,并且在受访者多次回答调查时会出现一些情况,因此数据中存在多行。像这样:

Id Question1
1     5
1     3
2     3
3     5
4     1

我想将数据转换/重新整形为宽格式,我可以这样:

Id Question1 Question1.v2
1     5          3
2     3        missing  
3     5        missing
4     1        missing

2 个答案:

答案 0 :(得分:0)

这可以帮到你:

missing

我建议您不要使用NA,而是使用df %>% group_by(Id) %>% mutate(row = paste0("Question1.v", row_number())) %>% ungroup() %>% spread(row, Question1) %>% rename(Question1 = Question1.v1) %>% mutate_all(function(x) ifelse(is.na(x), "missing", x)) # # A tibble: 4 x 3 # Id Question1 Question1.v2 # <int> <int> <chr> # 1 1 5 3 # 2 2 3 missing # 3 3 5 missing # 4 4 1 missing ,这样您仍然可以将变量视为数字。

如果您因任何原因想要完全匹配输出,请尝试以下方法:

Url.Action

答案 1 :(得分:0)

使用数据表包,您可以执行以下操作:

library(data.table)
dat1 <- data.table(Id = c(1, 1, 2, 3, 4), Question1 = c(5, 3, 3, 5, 1))

如果你有数据帧df1,你应该先做setDT(df1)把它变成数据表。

dat1[, temp := paste0("Question1.V", 1:.N), by = Id]
res <- dcast(dat1, Id ~ temp, value.var = "Question1")
names(res)[2] <- "Question1"

> res
   Id Question1 Question1.V2
1:  1         5            3
2:  2         3           NA
3:  3         5           NA
4:  4         1           NA