将一列移到另一列下

时间:2019-03-11 09:49:24

标签: r

enter image description here 嗨,

如何在交易阶段将s1移至s2下,并将日期移至d1和d2。

要实现这一目标?

enter image description here

因此在R中,我将所有阶段列重命名为“ s”,将日期列重命名为“ d”。然后我尝试了:

data_tidied <- data %>% 
select(-Name) %>%
mutate_all(as.character) %>%
gather(key, value, -ID) %>%
filter(value != "") %>%
spread(key)

由于最后一行而引发此错误:eval_tidy(enquo(var),var_env)中的错误:找不到对象“

1 个答案:

答案 0 :(得分:0)

data.table方法

样本数据

data <- structure(list(ID = c(1, 2, 3, 4), Name = c("a", "b", "c", "d"
), `Deal Stage` = c("new", "lost", "won", "old"), Date = structure(c(1489017600, 
1482451200, 1484697600, 2430259200), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), s1 = c("contact", "contracted", "verbal confirmation", 
"proposal sent"), d1 = structure(c(1488844800, 1482278400, 1484352000, 
1482278400), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
    s2 = c("new leads", NA, "proposal sent", NA), d2 = structure(c(1488758400, 
    NA, 1482278400, NA), class = c("POSIXct", "POSIXt"), tzone = "UTC")), row.names = c(NA, 
-4L), class = c("tbl_df", "tbl", "data.frame"))

代码

library( data.table )
#make data a data.table, 
setDT(data)
#rename cols Deal Stage and Date to s0 and d0, for easy melting
setnames( data, c("Deal Stage", "Date"), c("s0", "d0"))
#melt, using patterns for deal_stage and date (hence the renaming in the previous line)
result <- melt( data, 
                id.vars = c("ID", "Name"), 
                measure.vars = patterns( Deal_Stage = "^s[0-9]", Date = "^d[0-9]" ) )
#remove NA's
result[ !is.na( Deal_Stage ), ][]

输出

#    ID Name variable          Deal_Stage       Date
# 1:  1    a        1                 new 2017-03-09
# 2:  2    b        1                lost 2016-12-23
# 3:  3    c        1                 won 2017-01-18
# 4:  4    d        1                 old 2047-01-05
# 5:  1    a        2             contact 2017-03-07
# 6:  2    b        2          contracted 2016-12-21
# 7:  3    c        2 verbal confirmation 2017-01-14
# 8:  4    d        2       proposal sent 2016-12-21
# 9:  1    a        3           new leads 2017-03-06
# 10: 3    c        3       proposal sent 2016-12-21