将for循环的结果保存为R中的向量

时间:2016-06-23 17:54:39

标签: r for-loop vector

我正在进行一项实验,该实验涉及人们聆听一系列音调(高音或低音)并计算高音。我有一个矢量他们实际听到了多少音(总):

count=c(1, 3, 5, 4, 3, 1, 2, 4, 3, 5, 2)

所有参与者都按照特定顺序听取了同一系列音调的子集:

list=c("high", "low", "low", "low", "high", "low", "high", "low", 
       "high", "high", "low", "low", "high", "low", "low")

我想知道每个参与者实际听到多少高音。因此,在这个例子中,如果他们总共听到3个音调,他们只听到一个高音,但如果他们总共听到5个音,他们就会听到2个高音。

为此,我尝试使用for循环来计算" high"的出现次数。对于每个参与者:

for (i in count){
  cat(length(grep("high", list[1:i])))
}

打印出所有正确数量的高音(在本例中为11211111121)。但是,我想创建并将此输出存储为单个值的向量。

我的问题是,如何将此for循环的输出保存为值向量?

2 个答案:

答案 0 :(得分:0)

这将每个值存储为向量中的一个条目。

tones <- c("high", "low", "low", "low", "high", "low", "high", "low", 
       "high", "high", "low", "low", "high", "low", "low")

count <- c(1, 3, 5, 4, 3, 1, 2, 4, 3, 5, 2)

x <- NULL
for (i in 1:length(count)){
x[i]  <-  length(grep("high", list[1:count[i]]))
}

> x
 [1] 1 1 2 1 1 1 1 1 1 2 1

答案 1 :(得分:0)

通常最好避免在R中使用import os import commands import glob #Global Commands glcmd = 'get_time_length' print("Preparing for kiosk mode! Press CTRL+C to exit") try: while 1: path = '/media/*/button1/*' os.system('mplayer -fs -quiet -slave path') line = os.popen(glcmd).readline().strip() #Get the duration from mplayer duration = line.split('=')[1] #Get just the length of video in Seconds print(duration) sleep(duration) #Wait until the video is done os.system('quit') 循环。

for
相关问题