我有一个数据框,对于该df中包含的某些列(我在名为Variables的向量中收集的名称),我想计算观察值的变量值的比率,除以第一个该观察组的观察值,不为零。
我该怎么做?我尝试了以下方法:
if (Condition==1){
for(i in 1:length(Variables)){
colNum <- which(colnames(df)== Variables[i])
df <- df %>%
group_by(Id) %>%
mutate(Column = .[[colNum]]/first(.[.[[colNum]]!=0, colNum][[1]]))
}
}
但这给了我以下错误:
Error in mutate_impl(.data, dots) :
Column `Column` must be length 6 (the group size) or one, not 246