如何在R数据帧中将数据从第i行2列更新到第j行1列? [英] How to update data from column i row 2 to column j row 1 in R dataframe?

查看:47
本文介绍了如何在R数据帧中将数据从第i行2列更新到第j行1列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含12个数据点的列i.我想将第2列的第i列复制到第j列的第1行.对其余的行重复此模式.然后将第j列的第12行分配给第i列的第1行.因此,如果第i列从1到12,第j列将从2、3,4 ... 12,1.最后一点似乎很容易做到,但是我在第一部分的for循环中苦苦挣扎.我不确定这是否是最好的方法.

I have a column i with 12 data points. I want to copy column i, row 2 to column j row 1. Repeat this pattern for the rest of the rows. Then assign column j row 12 column i row 1. So, if column i went from 1 to 12. Column j would go from 2, 3,4...12, 1. The last bit seems easy to do, but I'm struggling with the for loop for the first part. I'm not sure if that's the best approach or not.

col.i <- rnorm(12,5,2)
df <- data.frame(col.i)
for(i in df$col.i){df$col.j <- df$col.i[i+1]}
Edit: It picks a random row from col.i and duplicates it in column j
df$col.j[12] <- df$col.i[1] 

推荐答案

这是一种dplyr方法,由于使用deault选项假定您的数据不存在na,因此有点不可靠,并且您始终希望第一个值位于col.i是col.j中的最后一个值.

This is a dplyr approach, its a bit hacky as it assumes your data has no na's by using the deault option, and that you always want the first value in col.i to be the last value in col.j.

library(dplyr)
answr <- df %>% 
  mutate(col.j = lead(col.i, default = col.i[1]))

这篇关于如何在R数据帧中将数据从第i行2列更新到第j行1列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆