[英]Reshaping a data based one two columns
I have a data like this:我有这样的数据:
df<-structure(list(id = c(13186082L, 13186082L, 15186082L, 15186082L,
32186082L, 32186082L, 24186085L, 24186085L), freq1 = c("socialinteraction2",
"who", "socialinteraction2", "who", "socialinteraction2", "who",
"socialinteraction2", "who"), Response = c("2", "a", "1", "b",
"3", "a", "4", "c")), class = "data.frame", row.names = c(NA,
-8L))
id freq1 Response
1 13186082 socialinteraction2 2
2 13186082 who a
3 15186082 socialinteraction2 1
4 15186082 who b
5 32186082 socialinteraction2 3
6 32186082 who a
7 24186085 socialinteraction2 4
8 24186085 who c
I want to reshape it in a way that selects the "Response" when freq1="who" and repeat the number of "Response" when freq1="socialinteraction2" in the way like this:我想以这样的方式重塑它,即在 freq1="who" 时选择“Response”,并在 freq1="socialinteraction2" 时重复“Response”的数量,如下所示:
From To
1 socialinteraction2 a
2 socialinteraction2 a
3 socialinteraction2 b
4 socialinteraction2 a
5 socialinteraction2 a
6 socialinteraction2 a
7 socialinteraction2 c
8 socialinteraction2 c
9 socialinteraction2 c
10 socialinteraction2 c
So, for instance, for the first Id, I want to make two columns.因此,例如,对于第一个 Id,我想制作两列。 For "to" when "freq1" is who selects "a" 2 times and all the "from" values will be "socialinteraction2.
对于“to”,当“freq1”是选择“a”2 次的人时,所有“from”值将是“socialinteraction2。
Is this what you were looking for:这是你要找的吗:
df<-structure(list(id = c(13186082L, 13186082L, 15186082L, 15186082L, 32186082L, 32186082L, 24186085L, 24186085L),
freq1 = c("socialinteraction2", "who", "socialinteraction2", "who", "socialinteraction2", "who",
"socialinteraction2", "who"),
Response = c("2", "a", "1", "b", "3", "a", "4", "c")), class = "data.frame", row.names = c(NA, -8L))
#separat socialinteraction2 and who into 2 columns
output <-df %>% pivot_wider(names_from= freq1, values_from = Response)
#create the repeating values
repeats <- rep(output$who, times=as.integer(output$socialinteraction2))
data.frame(From=c("socialinteraction2"), To=repeats)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.