[英]R: loop through unique values of column and compute new variables
我試圖通過引用一列(SID)中的唯一值來遍歷數據集。 我想基於數據框中的現有列創建幾個變量。 這些將針對SID的每個唯一值進行計算。 目前,我的代碼並未根據SID的唯一值進行分離。 它是對整個數據集的值求和。
這是一個例子:
數據:
數據框中有40行。 SID中有20行的值為“ 9003”,而有20行的值為“ 1028”。
我想創建一個變量和名為“ numPR”的列,它是df中已存在的列的值之和(“ PreviewRound”)。 “ PreviewRound”中的值為0或1s。
在此特定示例中,對於SID的每個唯一值,numPR應該為6,但是當前為12(不按SID分隔)。
這是代碼:
file = "fpd_2b.csv"
headers = read.csv(file, header = F, nrows = 1, as.is = T)
df = read.csv(file, skip = 2, header = F)
colnames(df) = headers
# Remove blank rows (there is a blank row between each unique SID)
df = subset(df, SID >1)
df$SID = factor(df$SID)
for (sid in unique(df$SID)) {
numPR = sum(df$PreviewRound)
df$numPR = numPR
}
numPR的整個列都用12填充,但是應該用6填充(9003為6,1028為6)。 任何幫助將非常感激! 我已經檢查了Stack Overflow和其他網站上的類似帖子,但是還沒有碰到我的問題。 我確信解決方案非常簡單,非常感謝您的幫助!
如果要創建列,請使用“ SID”作為分組變量
df$numPR <- with(df, ave(PreviewRound, SID, FUN = sum))
或者,如果我們想要匯總的輸出,請使用aggregate
aggregate(PreviewRound~ SID, df, FUN = sum)
OP代碼的問題是如何替換值
df$numPR = numPR
在OP的for
循環中,更重要的是
numPR = sum(df$PreviewRound)
正在獲取整個“ PreviewRound”列的sum
每次for
循環運行時,“ numPR”列都會更新for
僅留下last
更新的unique
“ SID”的一個sum
。 為了避免這種情況,請使用索引
df$numPR <- NA
for (sid in unique(df$SID)) {
i <- df$SID == sid # create a logical index
numPR = sum(df$PreviewRound[i]) # subet the data based on the index
df$numPR[i] = numPR # assign the values only to those selected rows
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.