R:在数据帧单列UP中移位值 [英] R: Shift values in single column of dataframe UP
本文介绍了R:在数据帧单列UP中移位值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用这样的示例数据:
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列中的所有值向上移动两行,而数据帧的其余部分保持不变。
结果应如下所示:
I would like to shift all values in the z column upwards by two rows while the rest of the dataframe remains unchanged. The result should look like this:
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
我只找到了将列的值向下移动或移动整个数据框的方法。
I only found ways to move the values of a column down, or a shifting of the whole dataframe.
任何想法?
谢谢!
Any ideas? Thanks!
推荐答案
您的问题简化为:
- 删除向量中的第一个
n
元素 - Pad
n
值
NA
在结尾
- Drop the first
n
elements in a vector - Pad
n
values ofNA
at the end
你可以做这有一个简单的功能:
You can do this with a simple function:
shift <- function(x, n){
c(x[-(seq(n))], rep(NA, n))
}
example$z <- shift(example$z, 2)
结果:
example
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
这篇关于R:在数据帧单列UP中移位值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文