从多个文件中查找回文

时间:2016-10-27 17:02:22

标签: r dataframe

我是R编程语言的新手。

我必须阅读大约100个txt文件并从中读取逗号分隔值。这些值采用以下格式 - "名称","性别","计数"和"年"。

我能够做到这一点......

问题:

我需要解析该文件的每个名称,并查找是否是回文。

我尝试了几种方法,但无法做到这一点。

代码:

list_of_files <- list.files(pattern = '.txt') 
counter = 1879
result_palindrom = 0
inter_palindrom = 0
# Function which checks if a word is palindrom or not
is_palindrome <- function(word){
  charsplit <- strsplit(word, "")[[1]]
  revchar <- rev(charsplit)
  all(charsplit==revchar)
}

# We need to append all the data into one file
for (year in 1880:1970){
  cur_data = read.table(list_of_files[year-counter],header = FALSE,sep = ",", col.names = c("name","sex","count"), fill = TRUE, strip.white = TRUE)
  cur_data$year <- year
  cur_data = cur_data[,c(4,1,2,3)]
  cur_data$palindrom = cur_data[is_palindrome(cur_data$name), ]
  inter_palindrom = rbind(inter_palindrom, cur_data)
}

print(inter_palindrom)

错误消息

Error in strsplit(word, "") : non-character argument
Called from: strsplit(word, "")

任何人都可以帮助我吗?

数据看起来像这样:

Name | Sex | Count | Year
X       M      100    1880
Y       F      80     1884
Z       M      90     1882

不同年份的所有数据都在单独的年份

0 个答案:

没有答案