使用for循环基于字符串创建文件名的困难

时间:2019-04-09 19:12:38

标签: r for-loop vector

我正在基于字符串序列创建文件名向量。字符串“ ABcd”应产生文件名“ mypath / A.txt”,“ mypath / B.txt”,“ mypath.cc.txt”和“ mypath / dd.txt”的向量。

我正在使用for循环尝试此操作,但是结果向量仅包含最后一个文件名。我的代码又长又低效。我想知道1)为什么它不起作用,以及2)关于更好编码的任何建议。

mystring <- "ABcd"

# count number of characters
stringlength <- nchar(mystring)

# define file path 
filepath <- "mypath"

# initialize vectors
filename <- rep("NA", stringlength)
files <- rep("NA", stringlength)
symbol <- rep("NA", stringlength)
prefix <- "NA"

# create filename prefix from letters in mystring - caps are single and lowercase are double
for (i in stringlength) 
{
  symbol[i] <- substring(mystring, i, i)
  if (symbol[i] %in% letters) {
    prefix <- paste(symbol[i], symbol[i], sep = "")
  } else {
    prefix <- symbol[i]
  }
  filename[i] <- paste(filepath, "/", prefix, ".txt", sep="")
  files <- c(files, filename[i])
}

1 个答案:

答案 0 :(得分:0)

好像我有两个错误。首先,正如我所指出的,我的for循环是错误的,并且没有按需要循环字符数。用“ for(i seq_len(string length))”替换“ for(i in string length)”可以更正此问题。

第二,“ files <-c(files,filename [i])”行使循环将新条目添加到预先存在的NA中,而不仅仅是给出所需的文件名向量。使用“ files [i] <-filename [i]””替换为适当的索引可解决此问题。

mystring <- "ABcd"

# count number of characters
stringlength <- nchar(mystring)

# find filename for image corresponding to symbol
filepath <- "/Users/mypath"

# initialize vectors
filename <- rep("NA", stringlength)
files <- rep("NA", stringlength)
symbol <- rep("NA", stringlength)
prefix <- "NA"

# create filename prefix from letters in mystring - caps are single and lowercase are double
for (i in seq_len(stringlength)) 
{
  symbol[i] <- substring(mystring, i, i)
  if (symbol[i] %in% letters) {
    prefix <- paste(symbol[i], symbol[i], sep = "")
  } else {
    prefix <- symbol[i]
  }
  filename[i] <- paste(filepath, "/", prefix, ".txt", sep="")
files[i] <- filename[i]
}
files
1] "/Users/mypath/A.txt"  "/Users/mypath/B.txt"  "/Users/mypath/cc.txt" "/Users/mypath/dd.txt"