【发布时间】:2014-07-06 06:45:20
【问题描述】:
我现在正在学习 R,我无法以有效的方式循环 R,虽然我可以使用 for 循环以非常复杂的方式进行字符串解析,但我对如何在矢量化方式。
例如
#Social security numbers in the United States are represented by
# numbers conforming to the following format:
#
# a leading 0 followed by two digits
# followed by a dash
# followed by two digits
# followed by a dash
# finally followed by four digits
#
# For example 023-45-7890 would be a valid value,
# but 05-09-1995 and 059-2-27 would not be.
#
# Implement the body of the function 'extractSecuNum' below so that it
# returns a numeric vector whose elements are Social Security numbers
# extracted from a text, i.e., a vector of strings representing the text lines,
# passed to the function as its 'text' argument.
# (You can assume that each string in 'text' contains
# either zero or one Social Security numbers.)
extractSecuNum = function(text){
# Write your code here!
x = 1:length(text)
list_of_input = rep(0, length(text))
for (ind in x){
list_of_input[ind] = sub(' .*', '', sub('^[^0-9]*', '', text[ind]))
}
temp = c()
for (ind in x){
if(list_of_input[ind] != ''){
temp = c(temp, list_of_input[ind])
}
}
temp2 = c()
for (ind in 1:length(temp)){
temp3 = strsplit(temp[ind], '-')
temp2 = c(temp2, temp3)
}
final = c()
for(ind in 1:length(temp2)){
if (sub('0[0-9][0-9]', '', temp2[[ind]][1]) == ''){
if (sub('[0-9][0-9]', '', temp2[[ind]][2]) == ''){
if (sub('[0-9]{4}', '', temp2[[ind]][3]) == '')
{ final = c(final, paste(temp2[[ind]][1], temp2[[ind]][2], temp2[[ind]][3], sep='-')) }
}
}
}
return(final)
}
这些是其他类似问题的问题,如果你仔细研究一下,你会发现第二个问题非常复杂和不优雅
https://gist.github.com/anonymous/c1c68121323af19c766c
我认为问题是R中的原子变量是一个数组,我无法访问字符串中的字符
任何建议将不胜感激
【问题讨论】:
-
你能给你的
extractSecuNum提供样本输入吗? -
if (nchar(x <- gsub('[^0-9]', '', text)) == 9) paste(substr(x, 1, 3), substr(x, 4, 5), substr(x, 6, 9), sep = '-')但如果有其他数字恰好包含九位数字,则不可靠。这是可行的,因为该问题假设 SSN 为零或一个。 -
@extracSecuNum
testInput = c( 'For example', '023-45-7890', 'would be a valid value', 'but 05-09-1995', 'and 059-2-27 would not be.', 'Also 011-99-2234 is okay.' ) correctOutput = c( '023-45-7890', '011-99-2234' )这些是我的测试输入,它们有效 -
@rawr 我知道我的解决方案并不严谨,我现在只是想学习在 R 中进行解析的一般方法,在 R 中解析与在 python 中解析确实不同,这有点令人困惑对我来说