2015-06-22 183 views
0

這段代碼是假設取一個單詞,並根據單詞中字母的位置計算單詞字母的值。因此,對於像「爆發」這是假設計算值字母「r」和「K」我是否正確使用sapply?

strg <- 'broke' 

#this part stores everything except the first, 
#last, and middle position of the word 

strg.leng <- nchar(strg) 

other.letts <- sequence(strg.leng) 

if (length(other.letts) %% 2 != 0) { 

    oth_let1 <- other.letts[-c(1, ceiling(length(other.letts)/2), length(other.letts))] 

} else { 

    oth_let0 <- other.letts[-c(1, c(1,0) + floor(length(other.letts)/2), length(other.letts))] 

} 

print(paste("Values of the other letters of: ", strg)) 

#here is where the computation starts, taking in the objects created above 

if ((nchar(strg) %% 2) != 0) { 

    sapply(oth_let1, function(i) print(paste(oth_let1[i], "L", (.66666*1.00001) - (oth_let1[i] - 1) *.05))) 

} else { 

    sapply(oth_let0, function(i) print(paste(oth_let0[i], "L", (.66666*1.00001) - (oth_let0[i] - 1) *.05))) 

} 

然而,對於「爆料」我知道這裏面是隻計算的「K」值和一個字一些其他的東西:

[1] "4 L 0.5166666666" 
[1] "NA L NA" 
[1] "4 L 0.5166666666" "NA L NA" 

雖然所需的輸出應該是兩個「R」和「k」的值,所以是這樣的:

我在做什麼錯?我錯誤地使用了sapply嗎?

+0

爲什麼你使用'oth_let0 [i]'?它應該是簡單的「我」。而「如果其他」在那裏是多餘的。你應該簡單地放一個sapply(並使用一個變量而不是兩個:'oth_let0'和'oth_let1')。並且,看看[這](http://stackoverflow.com/questions/19480652/sapply-in-r-why-returns-input)瞭解最後一個。 – m0nhawk

回答

2

sapply遍歷提供的向量或列表,並依次爲每個成員提供函數。在你的情況下,你得到值2和4,然後嘗試使用自己的值再次索引你的向量。由於oth_let1向量只有兩個成員,因此您會得到NA。您可以通過用i替換oth_let1[i]來修復當前的代碼。但是,您的代碼可以大大簡化爲:

strg <- 'broke' 
lets <- 2:(nchar(strg) - 1) 
lets <- lets[-(1:2 + length(lets))/2] # removes middle item for odd and middle two for even 
cat("Values of the other letters of:", strg, "\n") 
#here is where the computation starts, taking in the objects created above 
writeLines(paste(lets, "L", 0.66666*1.00001 - (lets - 1) * 0.05, sep = " ")) 

我假設您要輸出結果到控制檯。

+0

哇,好吧,你已經簡化了多少。 – Nolohice

1

您正在使用sapply正確,您遇到的問題是其中的功能。你想要的是other.letts變量的i元素,而不是oth_let1oth_let1具有來自other.letts的索引。

代碼波紋管應該工作,我也改變變量的名稱爲oth_let,所以你不必使用其他if。對於輸出是確切的,你要求我使用invisible函數。

strg <- 'broke' 
strg.leng <- nchar(strg) 

other.letts <- sequence(strg.leng) 

if(length(other.letts) %% 2 != 0) { 
    oth_let <- other.letts[-c(1, ceiling(length(other.letts)/2), 
         length(other.letts))] 
}else{ 
    oth_let <- other.letts[-c(1, c(1,0) + floor(length(other.letts)/2), 
         length(other.letts))] 
} 

print(paste("Values of the other letters of: ", strg)) 

invisible(sapply(oth_let, 
       function(i) 
       print(paste(other.letts[i], "L", (.66666*1.00001) - (other.letts[i] - 1) *.05))))