使用这样的示例数据:
example=data.frame(x=c(1,2,3,4,5,6,7,8), y=c(1,2,3,4,5,6,7,8), z=c(1,2,3,4,5,6,7,8))
看起来像这样:
x y z
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6
7 7 7 7
8 8 8 8
我想将z列中的所有值向上移动两行,而其余的数据帧保持不变。 结果应如下所示:
x y z
1 1 1 3
2 2 2 4
3 3 3 5
4 4 4 6
5 5 5 7
6 6 6 8
7 7 7 NA
8 8 8 NA
我只找到了将列的值向下移动或移动整个数据帧的方法。
有什么想法吗? 谢谢!
答案 0 :(得分:11)
您的问题简化为:
n
元素放入向量n
的{{1}}个值您可以使用一个简单的功能执行此操作:
NA
结果:
shift <- function(x, n){
c(x[-(seq(n))], rep(NA, n))
}
example$z <- shift(example$z, 2)
答案 1 :(得分:2)
example = tibble(x=c(1,2,3,4,5,6,7,8),
y=c(1,2,3,4,5,6,7,8),
z=c(1,2,3,4,5,6,7,8))
example %>% mutate_at(c("z"), funs(lead), n = 2 )
# A tibble: 8 x 3
x y z
<dbl> <dbl> <dbl>
1 1.00 1.00 3.00
2 2.00 2.00 4.00
3 3.00 3.00 5.00
4 4.00 4.00 6.00
5 5.00 5.00 7.00
6 6.00 6.00 8.00
7 7.00 7.00 NA
8 8.00 8.00 NA
答案 2 :(得分:1)
我找不到好的副本,所以这是使用length<-
shift2 <- function(x, n) `length<-`(tail(x, -n), length(x))
# or just shift2 <- function(x, n) c(tail(x, -n), rep(NA, n))
transform(example, z = shift2(z, 2))
# x y z
# 1 1 1 3
# 2 2 2 4
# 3 3 3 5
# 4 4 4 6
# 5 5 5 7
# 6 6 6 8
# 7 7 7 NA
# 8 8 8 NA
答案 3 :(得分:0)
## In case you want to shift your rows down by one step for only one column
`z <- example$'z'`
# Deleting the last z value in order to shift values
# ahead by one period to realign with other rows
z_1 <-head(z,-1)
# We set the initial z value to zero
for (i in 1: (length(z)+1)) {
if(i != 1){
z[i] = Z_1[i-1]}
else{
z[i] = 0
}
}
Z
# Append Z to dataframe
example$z <- z
答案 4 :(得分:-1)
“有用”包中的此函数可在两个方向上移动列: https://www.rdocumentation.org/packages/useful/versions/1.2.6/topics/shift.column