希望我的for循环在R中返回字母而不是数字

时间:2016-02-02 16:21:22

标签: r for-loop variable-assignment assign

for(k in seq(0,length(Gs@left)-nl,len=30))
{
fcs <- abs(fft(Gs@left[(k+1):(k+nl)]))
tmp <- lsfit(X,fcs,inter=F)
print(order(-tmp$coef)[1])
}

我有一个返回数字列表的for循环:

[1] 3
[1] 1
[1] 1
[1] 2

这些数字对应于钢琴上的音符,对于它来说,返回G4而不是1,A4而不是2等等会更有用...

有没有办法编写我的for循环来返回它(即1 =&#34; G4&#34;等......)?

我尝试过分配(粘贴(&#34; G4&#34;),1),但这不起作用。

谢谢

5 个答案:

答案 0 :(得分:3)

由于缺乏必要的信息而不是确切的答案,但这应该给你一些提示

import time
import numpy as np

np.__config__.show() #make sure BLAS/LAPACK is being used
np.random.seed(seed = 0)

#initialize data matrix X and label vector Y
n_rows, n_cols = 1e6, 100
X = np.random.random(size=(n_rows, n_cols))
Y = np.random.randint(low=0, high=2, size=(n_rows, 1))
Y[Y==0] = -1
Z = X*Y # all operations are carried out on Z

def compute_logistic_loss_value_and_slope(rho, Z):
    #compute the value and slope of the logistic loss function in a way that is numerically stable
    #loss_value: (1 x 1) scalar = 1/n_rows * sum(log( 1 .+ exp(-Z*rho))
    #loss_slope: (n_cols x 1) vector = 1/n_rows * sum(-Z*rho ./ (1+exp(-Z*rho))
    #see also: https://stackoverflow.com/questions/20085768/

    scores = Z.dot(rho)
    pos_idx = scores > 0
    exp_scores_pos = np.exp(-scores[pos_idx])
    exp_scores_neg = np.exp(scores[~pos_idx])

    #compute loss value
    loss_value = np.empty_like(scores)
    loss_value[pos_idx] = np.log(1.0 + exp_scores_pos)
    loss_value[~pos_idx] = -scores[~pos_idx] + np.log(1.0 + exp_scores_neg)
    loss_value = loss_value.mean()

    #compute loss slope
    phi_slope = np.empty_like(scores)
    phi_slope[pos_idx]  = 1.0 / (1.0 + exp_scores_pos)
    phi_slope[~pos_idx] = exp_scores_neg / (1.0 + exp_scores_neg)
    loss_slope = Z.T.dot(phi_slope - 1.0) / Z.shape[0]

    return loss_value, loss_slope


#initialize a vector of integers where more than half of the entries = 0
rho_test = np.random.randint(low=-10, high=10, size=(n_cols, 1))
set_to_zero = np.random.choice(range(0,n_cols), size =(np.floor(n_cols/2), 1), replace=False)
rho_test[set_to_zero] = 0.0

start_time = time.time()
loss_value, loss_slope = compute_logistic_loss_value_and_slope(rho_test, Z)
print "total runtime = %1.5f seconds" % (time.time() - start_time)

答案 1 :(得分:2)

编写一个函数来进行翻译可能最有意义。

strfnote <- function(notes, base_octave=4) {
  paste0(LETTERS[(notes %% 7) + 1], trunc(notes / 7) + base_octave)
}

哪会给我们

> strfnote(0:10)
 [1] "A4" "B4" "C4" "D4" "E4" "F4" "G4" "A5" "B5" "C5" "D5"

你可以让strfnote更加完整,处理诸如偶然事件之类的事情,并准确指定哪些注释对应于&#34; 0&#34;设置偏移量。但经过一些基本的处理后,你的代码可以生成数字,然后为了渲染你可以将它们传递给这个函数来获得一个可读的形式。

答案 2 :(得分:0)

尝试使用因素:

示例:

df['label'] = pd.Categorical(df['label'], categories=s.values, ordered=True)

print pd.pivot_table(df, index=['Name'], columns=['Ord', 'label'])
      Value                                              ...                  \
Ord       1                                              ...     2             
label    3M   1Y   2Y   3Y   5Y   7Y  10Y  15Y  20Y  25Y ...    1Y   2Y   3Y   
Name                                                     ...                   
ABC     0.1  0.1  0.1  0.1  0.1  0.1  0.1  0.1  0.1  0.1 ...   0.1  0.1  0.1   


Ord                                       
label   5Y   7Y  10Y  15Y  20Y  25Y  30Y  
Name                                      
ABC    0.1  0.1  0.1  0.1  0.1  0.1  0.1  

[1 rows x 22 columns]    

将返回

data <- c(1,2,3,4,5, 1,3,4)
labeled_data <- factor(data, labels = c("a1", "a2", "a3", "a4", "a5"))
labeled_data

答案 3 :(得分:0)

只需设置一个字符串,其中的音符符合您音乐惯例所暗示的顺序(我无法直觉,这完全是错误的,并且看到@ user295691实际上可能理解数学基础)。由于您只提供两个注释:

# Above the loop
notes=c("G4", "A4", "B4")   # not sure if third one is sensible musically
                            # would have guessed that A5 was next to G4
# in the loop
print( notes[ order(-tmp$coef)[1] ] )

答案 4 :(得分:0)

您可以构建一个列表pianoNotes并按索引[[i]]访问项目。

对于你的例子,这将是:

pianoNotes <- list("1" = "G4") # and more
for(k in seq(0,length(Gs@left)-nl,len=30))
{
  fcs <- abs(fft(Gs@left[(k+1):(k+nl)]))
  tmp <- lsfit(X,fcs,inter=F)
  print(pianoNotes[[order(-tmp$coef)[1]]])
}