data <- data.frame(id = factor(c(1,2,3,4,5,6,7,8,9,10)),name = factor(c("a","b","c","d","e","f","g","h","i","j")),date = factor(c(NA,"July",NA,"August",NA,"September",NA,"October",NA,"November")))
我想将第3列向上移动一个。所以它看起来像
头(数据)
id name date
1 a July
2 b NA
3 c August
4 d NA
5 e September
你能帮帮我吗?另外,我想知道这个过程是否会
与简单整数不同。
答案 0 :(得分:0)
使用tidyverse集合,您可以通过以下简单代码实现此目的:
library(tidyverse)
data <- data.frame(id = factor(c(1,2,3,4,5,6,7,8,9,10)),
name = factor(c("a","b","c","d","e","f","g","h","i","j")),
date = factor(c(NA,"July",NA,"August",NA,"September",NA,
"October",NA,"November")))
data$date %>% lead()
id name date
1 1 a July
2 2 b <NA>
3 3 c August
4 4 d <NA>
5 5 e September
如果变量类型是整数,则可以使用相同的过程。例如,如果要将“id”更改为整数,则可以使用相同的函数:
data$id %<>% as.character %>% as.numeric
data$id %>% lead()
id name date
1 2 a July
2 3 b <NA>
3 4 c August
4 5 d <NA>
5 6 e September