输入数据帧具有长格式,并包含一个用户的信息到多行。
实施例
for _ in (0..<questions.count).reversed(){
//YOUR CODE
}
d_long <- data.frame( nameid = c("sally","sally","sally","Robert","annie","annie"), value = c("product1","ra","ent","ra","ra","product1"))
怎么可能将它转换为这样的二进制数据帧:
nameid value
1 sally product1
2 sally ra
3 sally ent
4 Robert ra
5 annie ra
6 annie product1
d_exist <- data.frame(nameid = c("sally","Robert","annie"), product1 = c(1,0,1), ra = c(1,1,1), ent = c(1,0,0))
答案 0 :(得分:1)
@akrun为这个问题提供了很少的好选项,但其中一个选项可以是使用tidyr::spread
以宽格式转换。虽然OP没有明确提及是否可以多次出现nameid
和value
,但最好将count
包含在该组中。解决方案如下:
library(tidyverse)
d_long %>% group_by(nameid, value) %>%
mutate(count = n()) %>%
ungroup() %>%
spread(value, count, fill = 0) %>%
as.data.frame()
# nameid ent product1 ra
# 1 annie 0 1 1
# 2 Robert 0 0 1
# 3 sally 1 1 1