我正在尝试编写一个使用索引的功能 ,该功能接受键值对并将其堆叠。
这是我的数据:
mydata<-structure(list(groupA = c("Rugby for Chipmunks","Rugby for Chipmunks","Chafing Explained"),First = c(5,3.57142857142857,5,4.5),groupB = c("pylons for Priests","Eating Creosote","Eating Creosote"),Second = c(4,4,3.16666666666667,2.1666667),groupC = c("Wow for YOU!","Advanced Cats for Bears","Blue Paint Only","Mockingbirds"),Third = c(5,3,NaN,4),groupD = c("How to Sell Pigeons","How to Sell Pigeons","How to Sell Pigoens","Larger Boulders"),Fourth = c(4.3,4.1,3.4),groupE = c("Making Money with Pears","Making Money with Pears","Why Walnuts?","Responding to Idiots Part II"),Fifth = c(5,4.16666666666667)),row.names = c(NA,-4L),class = c("tbl_df","tbl","data.frame"))
我想使用索引,因为将来的任务将使用具有不同列名和宽度的数据框。我的方法使用一个函数来确定一列是否为奇/偶,然后提取成对的列,直到到达最后一个 odd 编号的列。请注意,该函数必须考虑每次提取时所需的奇偶索引顺序(组名和相应分数):
odd <- function(x) x%%2 != 0
outfile<-list()
moveit<-function(df){
for (i in 1:dim(df)[2]) # define number of loops
if ( i==dim(df)[2]-1 ) {break} # stop at least odd-numbered column
if ( odd(i)==FALSE) {next} # skip when i is not an odd numbered index
print(i)
outfile[[i+1]]<-df[,c(i,i+1)]
}
result<-moveit(mydata)
str(result)
您可以看到结果只是最后一个键值对。为什么?如何调整功能以将所有键值对提取到一个数据框中?