我是R的新手,正在尝试将以下段转换为循环:
tea_s_eachclicks=as.data.frame(matrix(nrow=1,ncol=12))
tea_s_eachclicks$V1=sum(mergetea_s[1:45,119:122]=='2')
tea_s_eachclicks$V2=sum(mergetea_s[1:45,123:126]=='2')
tea_s_eachclicks$V3=sum(mergetea_s[1:45,127:130]=='2')
tea_s_eachclicks$V4=sum(mergetea_s[1:45,131:134]=='2')
tea_s_eachclicks$V5=sum(mergetea_s[1:45,135:138]=='2')
tea_s_eachclicks$V6=sum(mergetea_s[1:45,139:142]=='2')
tea_s_eachclicks$V7=sum(mergetea_s[1:45,143:146]=='2')
tea_s_eachclicks$V8=sum(mergetea_s[1:45,147:150]=='2')
tea_s_eachclicks$V9=sum(mergetea_s[1:45,151:154]=='2')
tea_s_eachclicks$V10=sum(mergetea_s[1:45,155:158]=='2')
tea_s_eachclicks$V11=sum(mergetea_s[1:45,159:162]=='2')
tea_s_eachclicks$V12=sum(mergetea_s[1:45,163:166]=='2')
mergetea_s
具有12段,每段4列,应将其计入tea_s_eachclicks
,但前提是值是“ 2”
非常感谢每一个建议!
答案 0 :(得分:1)
您可以执行以下操作:
# Define constants (avoid magic numbers):
rows <- 1:45
cols_ref <- 119:122
n_steps <- 12
# Preallocate
tea_s_eachclicks <- as.data.frame()
for (i in 1:n_steps) {
tea_s_eachclicks[[paste0("V", i)]] <-
sum(mergetea_s[rows, cols_ref + 4*(i-1)] == '2')
}
由于您未提供可重复的数据,因此无法测试。