【发布时间】:2017-01-03 23:28:00
【问题描述】:
请注意:否决票对我没有帮助,只会通过降低其知名度来阻碍我解决这个问题。我请求 SO 社区评论如何改进这个问题以解决我的问题。
我有一个数据框,其中包含学生(Amy、Bob)的多个日期 (3),我想对学生和日期的子集执行某些操作。请考虑通过带有对象类转换的for循环过程来回答问题,而不是给出单行代码来解决这个问题。我需要在循环内运行两个函数。 第一个需要一个带有 (A,B) 的数字矩阵,第二个需要一个列表。 求和和除法运算只是为了说明。样本数据:
dput(jj)
structure(list(month = structure(c(1, 2, 3, 1, 2, 3, 1, 2, 3,
1, 2, 3), class = "Date"), student = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Amy", "Bob"), class = "factor"),
A = c(9, 7, 6, 8, 6, 9, 3, 2, 1, 5, 6, 5), B = c(6, 7, 8,
5, 6, 7, 5, 4, 6, 3, 1, 5)), .Names = c("month", "student",
"A", "B"), row.names = c(NA, -12L), class = "data.frame")
#necessary 表示由于对象类要求而假定为强制的步骤。这是代码:
dong<-data.frame()
IDs<-unique(jj$student)
uniq <- unique(jj$month)
king<-list() #necessary
for (i in IDs ){
for (j in uniq){
tmp <- jj[jj$student==IDs[i]& jj$month==uniq[j],]
tmp$month<-NULL
tmp$student<-NULL
tmp1 <- `dimnames<-`(as.matrix(tmp), NULL) #necessary
#storing column sums as list element
king[[1]][1]<- sum(tmp1[,1])
king[[1]][2]<- sum(tmp1[,2])
kong <- `dimnames<-`(do.call(cbind, lapply(king, as.numeric)), NULL) #necessary
#dividing column sums
bong<- kong[,1]/kong[,2]
dong<-rbind(dong,c(i,j,bong))
}}
但我得到了
Error in `*tmp*`[[1]] : subscript out of bounds
我也很困惑如何将每个学生和月份子集的操作结果保存在单个数据框中。 输出应如下所示:
# month student Bong
#1 1970-01-02 Amy 1.5454545
#2 1970-01-03 Amy 1.0000000
#3 1970-01-04 Amy 1.0000000
#4 1970-01-02 Bob 1.0000000
#5 1970-01-03 Bob 1.6000000
#6 1970-01-04 Bob 0.5454545
谢谢
【问题讨论】:
-
您的预期输出是什么?从代码中您要尝试做什么并不完全清楚
标签: r list for-loop matrix dataframe