[英]Spreading a character column by time and id r
Question in style with many others, but still different. 与许多其他人的风格问题,但仍然不同。 I often see people asking for a way to spread a column into several, but it is often in a df where there is a measurement for each name in the column. 我经常看到人们想要一种方法将列扩展成几个,但它通常在df中,其中列中的每个名称都有一个度量值。
Like this: 像这样:
head(df)
id time fish weight
1 1 1 marlin 4
2 1 1 cod 1
3 1 2 cod 1
4 2 1 salmon 2
5 2 1 cod 2
6 2 2 cod 3
So I can use spread like this (or dcast or similar: 所以我可以使用像这样的传播(或dcast或类似的:
df<-spread(df, fish,weight, fill=F)
id time cod marlin salmon
1 1 1 1 4 <NA>
2 1 2 1 <NA> <NA>
3 2 1 2 <NA> 2
4 2 2 3 <NA> <NA>
But what if you do not have a value (here weight) for the variable, but just want to spread the types of fish? 但是,如果你没有变量的值(这里是重量),但只是想传播鱼类? So output was like this 所以输出是这样的
id time Fish1 Fish2
1 1 marlin salmon
1 2 cod <NA>
2 1 salmon cod
2 2 cod <NA>
how do you do that? 你是怎样做的? Thank you for any help. 感谢您的任何帮助。 It is greatly appreciated. 非常感谢。
We need a group by sequence 我们需要按顺序分组
df %>%
select(-weight) %>%
group_by(id, time) %>%
mutate(ind = paste0("Fish", row_number())) %>%
spread(ind, fish)
# A tibble: 4 x 4
# Groups: id, time [4]
# id time Fish1 Fish2
# <int> <int> <chr> <chr>
#1 1 1 marlin cod
#2 1 2 cod NA
#3 2 1 salmon cod
#4 2 2 cod NA
df <- structure(list(id = c(1L, 1L, 1L, 2L, 2L, 2L), time = c(1L, 1L,
2L, 1L, 1L, 2L), fish = c("marlin", "cod", "cod", "salmon", "cod",
"cod"), weight = c(4L, 1L, 1L, 2L, 2L, 3L)), .Names = c("id",
"time", "fish", "weight"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.