扩展为循环代码,而不是循环代码的快捷方式

时间:2018-09-21 21:42:27

标签: r for-loop

y <- c()
for( position in c("cannon","jackson","benford","paws","moxie") ) {
n <- nchar(position)
y[position] <- letters[n]
}
y`

这是快捷方式代码,但是在尝试制作扩展代码时遇到了麻烦。必须有15行代码。

1 个答案:

答案 0 :(得分:1)

给出一个字符向量

import os
import sys
import csv

csvfile = '/Users/username/Documents/output.csv'

def main(args):

    # Open a CSV for writing outputs to
    with open(csvfile, 'w') as out:
        writer = csv.writer(out, lineterminator='\n')

        # Walk through the directory specified in cmd line
        for root, dirs, files in os.walk(args):
            for item in files:
                # Check if the item is a CSV
                if item.endswith('.csv'):
                    # If yes, read the first row
                    with open(item, newline='') as f:
                        reader = csv.reader(f)
                        row1 = next(reader)
                        # Write the first cell as the file name
                        f.write(os.path.realpath(item))
                        f.write(f.readline())
                        f.write('\n')
                        # Write this row to a new line in the csvfile var
                            # Go to next file

                # If not a CSV, go to next file
                else:
                    continue

                # Write each file to the CSV
                # writer.writerow([item])

if __name__ == '__main__':
    main(sys.argv[1])

任务是查找chars <- c("cannon", "jackson", "benford", "paws", "moxie") 的每个元素的字符数。然后,我们要获取此结果和相应的子集chars

第一种方法:复制并粘贴(请勿这样做)

letters

我想这就是您要避免使用的...

第二种方法:for循环(虽然R社区中的does not enjoy the best reputation很好)

nchar_cannon <- nchar(chars[1])
nchar_jackson <- nchar(chars[2])
nchar_benford <- nchar(chars[3])
nchar_paws <- nchar(chars[4])
nchar_moxie <- nchar(chars[5])

letter_cannon <- letters[nchar_cannon]
letter_jackson <- letters[nchar_jackson]
letter_benford <- letters[nchar_benford]
letter_paws <- letters[nchar_paws]
letter_moxie <- letters[nchar_moxie]

out <- c(letter_cannon,
         letter_jackson,
         letter_benford,
         letter_paws,
         letter_moxie)
setNames(out, chars)

第三种方法:使用a functional

out <- c()
for( position in c("cannon","jackson","benford","paws","moxie") ) {
n <- nchar(position)
out[position] <- letters[n]
}
out

第四种方法:vectorization(推荐)

sapply(chars, function(x) letters[nchar(x)])

基准

setNames(letters[nchar(chars)], chars)

enter image description here

library(microbenchmark)
chars_long <- c(replicate(1e6, chars))

benchmark <- microbenchmark(
  loop_fun = loop_fun(chars_long),
  functional_fun = functional_fun(chars_long),
  vectorize_fun = vectorize_fun(chars_long),
  times = 100L
)

autoplot(benchmark)

基准测试中使用的功能

#Unit: seconds
#           expr       min        lq      mean    median        uq      max neval
#       loop_fun  7.217346  8.142811  9.481697  9.431999 10.472183 13.54128   100
# functional_fun 10.540376 12.064269 13.062617 12.873895 13.738929 17.90349   100
#  vectorize_fun  1.227648  1.310427  1.450161  1.370944  1.552207  2.00134   100