如何遍历数据框中的列

How to loop through the columns in data frame

我有一个下面的向量h=c("a","b","c","d","e")

我想使用 lag() 函数创建看起来像这样的数据集:

pr <- data.frame(your_github         = h, 
                 review_this1        = lag(h),
                 review_this2        = lag(h,2))

但是,当我使用延迟时,会发生以下情况: col2=c(NA,"a","b","c","d") 和 col3=(NA,NA,"a","b", "c")

但我需要得到类似于 data.frame(col1=c("a","b","c","d","e"),col2=c("b","c","d","e","a"), col3=("c","d","e","a","b")) 的结果,其中 col2 和 col3 中的值是循环的(即第 2 列只是滞后 1 的第 1 列,但第 2 列中的第 1 项是 teh st 列中的最后一项)。

是这样的吗?

library(dplyr) 

h = c("a","b","c","d","e")
pr <- data.frame(your_github = h,
                 review_this1 = ifelse(is.na(lead(h)), h[1], lead(h)),
                 review_this2 = ifelse(is.na(lead(h, 2)), h[2:1], lead(h, 2)))
pr

#  your_github review_this1 review_this2
#1           a            b            c
#2           b            c            d
#3           c            d            e
#4           d            e            a
#5           e            a            b

使用基础 R,您可以使用 headtail(在 tio here 上测试)实现此目的:

h<-letters[1:5]
pr <- data.frame(your_github         = h, 
                 review_this1        = c(tail(h, -1), head(h, -1)),
                 review_this2        = c(tail(h, -2), head(h, -2)))
print(pr)

输出:

  your_github review_this1 review_this2
1           a            b            c
2           b            c            d
3           c            d            e
4           d            e            a
5           e            a            b

我们的想法是将向量 h 的开头与尾部相连接,并将其与 head 所采用的向量的结尾减去我们从尾部得到的内容相连接,这样我们就有相同的长度在数据框的每一列(向量)的末尾。

如果要循环最后一个值成为第一个值的向量,只需将tail和head中的符号反转即可。