这可能是一个简单的问题,但我无法在任何地方找到答案:(那你可以帮助我吗?
如果数据框看起来像这样:
"ID" "date"
A 01-03-2017
A 05-02-2016
B 08-03-2016
A 09-11-2012
B 02-03-2014
B 09-07-2013
C 23-08-2016
B 24-05-2017
C 12-12-2015
我希望它看起来像这样: `
"ID" "date.1" "date.2" "date.3" "date.4"
A 01-03-2017 05-02-2016 09-11-2012 NA
B 08-03-2016 02-03-2014 09-07-2013 24-05-2017
C 23-08-2016 12-12-2015 NA NA
然后将具有相同ID的所有行粘贴到彼此之后,为每一行创建一个新列。 我希望我能说清楚。有人可以告诉我该怎么做? 非常感谢,提前, 萨拉
答案 0 :(得分:0)
这是使用'spread'功能的解决方案。谢谢Markus
# Libraries
library(tidyverse)
# 1. Data set
df <- data.frame(
id = c("A", "A", "B", "A", "B", "B", "C", "B", "C"),
date = c("01-03-2017", "05-02-2016", "08-03-2016", "09-11-2012",
"02-03-2014", "09-07-2013", "23-08-2016", "24-05-2017", "12-12-2015"))
# 2. New feature 'value' the same as 'date'
df$value <- df$date
# 3. Use 'spread' from 'tidyverse'
# 3.1. Just 'spread'
spread(df, key = date, value = value)
# 3.2. 'spread' thanks 'Markus' for the solution
df %>%
group_by(id) %>%
mutate(date = seq_along(id)) %>%
spread(key = date, value = value, sep = ".")
希望它在某种程度上有所帮助