我想知道如何在for回圈完成一次迭代時,用新創建的 "p_"變數替換代碼中的 "x"。我們的目標是在回圈完成一次迭代時更新資料框并洗掉采樣的名字,這樣就不會多次選擇相同的名字。有什么方法可以將一個變數動態地輸入到這一行嗎?
我是R的新手,所以請原諒我!
我是R的新手。謝謝!
setwd('/Users/Mike/Desktop/Random Coding Projects/Draft Simulator') /span>
#加載可供征召的球員資料
df <- read.csv('Players.csv')
# 加載蛇形選秀位置資料
snake_pos <- read.csv('snake positions.csv')
# 要求用戶輸入征兵資訊。
# num_drafters <- readline(prompt='Enter the number of people participation in the draft: ')
# num_drafters <- as.integer(num_drafters)。
# num_rds <- readline(prompt='enter the number of rounds in the draft: ')
# num_rds <- as.integer(num_rds)
# pick_pos <- readline(prim = 'Enter your draft position: ')
# pick_pos <- as.integer(pick_pos)
# 明確定義選秀引數
num_drafters <- 10
num_rds <- 15
pick_pos <- 2
# Assign Picks to Teams[/span
t1_picks <- snake_pos[/span>1,]
pick_nos <- snake_pos[pick_pos,/span>]
t3_picks <- snake_pos[/span>3,]
t4_picks <- snake_pos[4,/span>]
t5_picks <- snake_pos[5,/span>]
t6_picks <- snake_pos[6,/span>]
t7_picks <- snake_pos[7,/span>]
t8_picks <- snake_pos[8,/span>]
t9_picks <- snake_pos[9,/span>]
t10_picks <- snake_pos[10,/span>]
# 定義團隊類別
base_team < - list(pl1 = '' , pl2 = '', pl3 = ', pl4 = '', pl5 = ', pl6 = '',
pl7 = '', pl8 = ', pl9 = '', pl10 = '', pl11 = ', pl12 = '',
pl13 = '', pl14 = ', pl15 = '')
class(base_team) <- 'team_template'
# 創建單個選取變數
total_picks <- num_drafters * num_rds
pick_list < - seq(1, total_picks,by=1)
for(i in pick_list) {>
assign(paste0('p_'。 i),sample(df[/span>1: 5。 3], 1。 替換= FALSE。 prob = NULL))
df <- df[! (df$PLAYER. NAME==x),】
}
uj5u.com熱心網友回復:
沒有任何df物件可以使用,但我不明白為什么這些東西不能作業:
set.seed(123) # for reproducibility
temp_players <- sample(df$PLAYER.NAME) # will be permuted vesion of that column.
for(i in pick_list) {>
assign(paste0('p_', i),sample(df[/span>1: 5。 3], 1。 替換= FALSE。 prob = NULL))
df <- df[/span>! (temp_players[i]==df$PLAYER. NAME), 】
# I'm assuming you would want to so something with the reduced dataset.
# Because if you don't it will get overwritten in next loop iteration
}
可能(事實上幾乎可以肯定),最好是制作一個df的副本,例如temp_df,然后用它來作業。你真的不應該對你的原始資料集進行破壞性的修改。
uj5u.com熱心網友回復:
我并不完全清楚你想要什么。 在這里使用一個Answer塊以方便閱讀。 Re:
# Creating Individual Pick Variables.
total_picks <- num_drafters * num_rds
pick_list < - seq(1, total_picks,by=1)
for(i in pick_list) {>
assign(paste0('p_'。 i),sample(df[/span>1: 5。 3], 1。 替換= FALSE。 prob = NULL))
df <- df[! (df$PLAYER. NAME==x),】
}
sample(df[1:5,3], 1, replace = FALSE, prob = NULL))將在for回圈的每次迭代中重置。 所以replace = FALSE沒有任何作用,因為你只選擇一個專案。
如果你想從df中隨機選擇一個pick_list數量的球員,不需要替換,那么:
total_picks <- num_drafters * num_rds
pick_list < - seq(1, total_picks,by=1)
randplayers <- sample(df[1: 5,3], pick_list。 替換= FALSE。 prob = NULL))
將給你一個隨機選擇的球員的矢量,沒有替換。 如果我在這個問題上偏離了軌道,請致歉。 BTW,還要注意的是,由于R是矢量的,for回圈通常是可以避免的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/332216.html
標籤:
